cyberwombat
cyberwombat

Reputation: 40084

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.

Upvotes: 46

Views: 47312

Answers (4)

DarkEmperor
DarkEmperor

Reputation: 5

You need to use the optional field with the options tag. Read the docs at https://express-validator.github.io/docs/api/validation-chain#optional

Upvotes: 0

Moshe Simantov
Moshe Simantov

Reputation: 4503

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

Upvotes: 122

Abdelsalam Shahlol
Abdelsalam Shahlol

Reputation: 1769

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.

Upvotes: 29

glortho
glortho

Reputation: 13200

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();

Upvotes: 4

Related Questions