Access request body in check function of express-validator v4 Access request body in check function of express-validator v4 express express

Access request body in check function of express-validator v4


After fiddling around for a while, I found a way to achieve this by using custom validators. The validator function passed to the custom method accepts an object containing the request body:

router.post(    "/submit",    [    // Check validity    check("email", "Invalid email").isEmail(),    check("password", "invalid password")        .isLength({ min: 4 })        .custom((value,{req, loc, path}) => {            if (value !== req.body.confirmPassword) {                // trow error if passwords do not match                throw new Error("Passwords don't match");            } else {                return value;            }        })    ],    (req, res, next) => {        // return validation results        const errors = validationResult(req);        // do stuff    });