I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why.
router.post(
'/login',
createValidationFor('email'),
checkValidationResult,
(req, res, next) => {
res.json({ allGood: true });
} );
function createValidationFor(type) {
switch (type) {
case 'email':
return [
check('email').isEmail().withMessage('must be an email')
];
case 'password':
return [
check('password').isLength({ min: 5 })
];
default:
return [];
}
}
function checkValidationResult(req, res, next) {
const result = validationResult(req);
if (result.isEmpty()) {
return next();
}
res.status(422).json({ errors: result.array() });
}
In a modified version of the code, I am attempting to access req inside the createValidationFor function. However, after doing so, the validation stops working:
router.post(
'/login',
createValidationFor,
checkValidationResult,
(req, res, next) => {
res.json({ allGood: true });
}
);
function createValidationFor(req, res) {
var type = req.body.type;
switch (type) {
case 'email':
return [
check('email').isEmail().withMessage('must be an email')
];
case 'password':
return [
check('password').isLength({ min: 5 })
];
default:
return [];
}
}
function checkValidationResult(req, res, next) {
const result = validationResult(req);
if (result.isEmpty()) {
return next();
}
res.status(422).json({ errors: result.array() });
}