Search code examples
node.jsexpress-validator

req.check is not function in express-validator?


Validator page where I am doing validation for password.

exports.userSignupValidator = (req, res, next) => {
    // check for password
    req.check('password', 'Password is required').notEmpty();
    req.check('password')
        .isLength({ min: 6 })
        .withMessage('Password must contain at least 6 characters')
        .matches(/\d/)
        .withMessage('Password must contain a number');
    // check for errors
    const errors = req.validationErrors();
    // if error show the first one as they happen
    if (errors) {
        const firstError = errors.map(error => error.msg)[0];
        return res.status(400).json({ error: firstError });
    }
    // proceed to next middleware
    next();
};

route page where I am defining signup route and taking userSignupValidation as middleware to validate password.

router.post("/signup", userSignupValidator, async(req, res) => {
    const {name, email, password} = req.body;
    try{
        await User.findByCredentials(name, email, password);
        const user = new User({
            name,
            email,
            password
        })
        await user.save();
        res.send({message: "Successfully Registered"});
    }
    catch(e){
        res.status(422).send({error: e.message});
    }
})

Why I am getting req.check is not function.


Solution

  • There are couple of things that are stopping your code from working properly, I will also advise that after this solution you take a look at the express-validator docs, pretty comprehensive. So let's get to it.

    Check function is in charge of adding your validation rules to the request body, while the validationResult is the function in charge of executing and ensuring that the request body body follows this rules. With that said, Here is how you would solve your problem.

    Since you love modularity, write your validation rules in a function like so :

    uservalidation.js

    const { check, validationResult } = require("express-validator") 
    
    //this sets the rules on the request body in the middleware
    const validationRules = () => {
        return [
            check('password')
            .notEmpty()
            .withMessage('Password is required')
            .isLength({ min: 6 })
            .withMessage('Password must contain at least 6 characters')
            .matches(/\d/)
            .withMessage('Password must contain a number'),
            //you can now add other rules for other inputs here, like username, email...
            // notice how validation rules of a single field is chained and not seperated
        ]
    }
    
    //while this function executes the actual rules against the request body
    const validation =  ()  => {
        return (req, res, next) => {
            //execute the rules
            const errors = validationResult(req)
            // check if any of the request body failed the requirements set in validation rules
            if (!errors.isEmpty()) {
                // heres where you send the errors or do whatever you please with the error, in  your case 
                res.status(400).json{error:errors}
                return
            }
            // if everything went well, and all rules were passed, then move on to the next middleware
            next();   
        }
    }
    
    
    

    Now in your actual route, you can then have this

    userroute.js

    //import the functions declared above.
    const { validationRules, validation } = require("./uservalidation.js")
    
    // for your sign up route
    
    // call the validationRules function, followed by the validation
    router.post("/signup", validationRules(),validation(), async(req, res) => {
        const {name, email, password} = req.body;
        try{
            await User.findByCredentials(name, email, password);
            const user = new User({
                name,
                email,
                password
            })
            await user.save();
            res.send({message: "Successfully Registered"});
        }
        catch(e){
            res.status(422).send({error: e.message});
        }
    })