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.
You can customize this behavior by passing an object with the following 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.
notEmpty() adds a validator to check if a value is not empty; that is, a string with a length of 1 or bigger. https://express-validator.github.io/docs/validation-chain-api.html#notempty. Follow this answer to receive notifications.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
According to the express-validator documentation: . bail() is useful to prevent a custom validator that touches a database or external API from running when you know it will fail. Can be used multiple times IN THE SAME validation chain if needed.
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
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 the following 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With