Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 710
cyberwombat Avatar asked Jul 10 '14 16:07

cyberwombat


People also ask

What is checkFalsy in express validator?

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.

What is not () in express validator?

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.

Which is better express validator or Joi?

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.

What is bail in express validation?

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.


2 Answers

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

like image 81
Moshe Simantov Avatar answered Sep 18 '22 21:09

Moshe Simantov


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.

like image 28
Abdelsalam Shahlol Avatar answered Sep 16 '22 21:09

Abdelsalam Shahlol