Express validator - how to allow optional fields
You can use the optional
method:
req.check('notexist', 'This works').optional().isInt();
Edit: See the docs here
As for express-validator 6
it's done like this:
check('email').isEmail().optional({nullable: true})
From documentation:
You can customize this behavior by passing an object with thefollowing options:
nullable: if true, fields with null values will be considered optional
checkFalsy: if true, fields with falsy values (eg "", 0, false, null)will also be considered optional
More info about optional rule.
That's the expected behavior, yes. The assumption of validation is that you want to act on a value of a known key. To get what you want, you could do something like this:
if(req.param('mykey')) req.check('mykey', 'This failed').isInt();