Search code examples
node.jsvalidationexpress

Express validator - how to allow optional fields


I am using express-validator version 2.3.0. It appears that fields are always required

req.check('notexist', 'This failed').isInt();

Will always fail - broken or am I missing something? There is a notEmpty method for required fields which seems to indicate the default is optional but I am not able to get the above to pass.


Solution

  • You can use the optional method:

    req.check('notexist', 'This works').optional().isInt();
    

    This won't work if the field is an empty string "" or false or 0 for that you need to pass in checkFalsy: true .optional({checkFalsy: true})

    An 422 status error will be thrown if you are only using .optional() & not passing any arguments.

    Edit: See the docs here