Home > front end >  Body errors not triggering express-validator
Body errors not triggering express-validator

Time:01-15

The validation middleware code is not triggered in the code I created, although all the logging flags are executed.

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            check(["email", "Must consist only of letters."]).isEmail();
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

I've tried sending req and req.body with check, as well as using body with both options. Console logs show a non-email string supplied, and I've tried other fields and other (failing) values.

Can anyone point me in a helpful direction? I've used older versions with checkBody, but I'm stuck with these. I've been fussing with app.js, but it's got no uncommented code right now.

CodePudding user response:

check returns a middleware, but you are not using this and passing the required args to it.

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            const middleware = check(["email", "Must consist only of letters."]).isEmail();
            middleware(req, res, next)
           
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

I'd suggest though this is a little unergonomic. It might not even work, because that middleware returned from check could call next, and then your code wouldn't make sense. It's designed to be used differently. It'd probably be cleaner to do like:

const { body, validationResult } = require("express-validator");

module.exports = {
    validateUsers: [
            body(["email", "Must consist only of letters."]).isEmail(),
            (req, res, next) => {
                const errors = validationResult(req);

                if (!errors.isEmpty()) {
                    return res.json(errors);
                }  else {
                    return next();
                }
            }
        ]
}

And then use like:

app.post('/thing', validateUsers, (req, res, next) => {
   // you'd get here only if there were no issues
})

  • Related