expressValidator is not a function even it specifies middleware must be function

//route.js
> const {body} = require('express-validator');
var validate=(method) =>{
    switch(method){
        case 'userRegistered':{
            return [
                body('username','Username doesnot exists').exists(),
                body('email','Invalid Email').exists().isEmail(),
                body('name','Invalid Email').optional(),
                body('password','password must be atleast 8 characters').exists().isLength({min:8,max:15}),
                body('Image','please upload your Image').exists(),

            ]
        }
    }
}
//route Handler
> router.post('/register-user',uploads.single('Image'),validate('userRegistered'),async(req,res)=>{
console.log(req.file);

const errors = validationResult(req)
if(!errors.isEmpty){
    res.status(422).json({errors:errors.array() });
}
await userRegistered(req.body,req.file.path,"client",res);
});
//app.js
> const expressValidator = require('express-validator');
  const bodyParser = require('body-parser');
  app.use(expressValidator());

// I use express validation as middleware in my REST API but got an error of
// app.use(expressValidator());
^

TypeError: expressValidator is not a function

8 thoughts on “expressValidator is not a function even it specifies middleware must be function”

  1. You require the check and validationResult objects from the package

    pass an array of check() calls as the second argument of the post() call. Every check() call accepts the parameter name as argument. Then we call validationResult() to verify there were no validation errors. If there are any, tell them to the client

    const { check, validationResult } = require('express-validator');
    
    app.post('/register-user', [
      check('name').isLength({ min: 3 }),
      check('email').isEmail(),
    ],async (req, res) => {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
      }
      //do something
    })
    
    Reply

Leave a Comment