Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for a presence of at least one parameter using express-validator

I'm using express and express-validator in my Nodejs app. I want to check for the presence of at least one of incoming parameters. Its sort of either or combination.

Lets say my service accepts 2 parameters. I want to be sure at least one of them is provided by the client.

The below code would work for just one. But I have no idea how to make it either or.

req.checkBody('param1', 'Mandatory field param1 not populated').notEmpty();
like image 639
Vahid Avatar asked Sep 28 '16 19:09

Vahid


People also ask

What does check do in express validator?

check([field, message])Creates a validation chain for one or more fields. They may be located in any of the following request objects: req. body.

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.13-Feb-2020.


2 Answers

Say you want to update a model that has id, status, and content... like a social media post, for example. Your controller may support updating the status of the model or its content. So, you could do something like the following:

export const updateModelValidation = [
    param('id').exists().isNumeric(), // <-- required model identifier
    oneOf( // <-- one of the following must exist
        [
          body('status').exists().isString(),
          body('content').exists().isString(),
        ],
    ),
];
like image 125
Leo Avatar answered Oct 02 '22 23:10

Leo


You could use multiple validation chains and use the oneOf function to validate against at least 1 validation chain.

https://www.npmjs.com/package/express-validator#oneofvalidationchains-message

like image 45
Dhwani Katagade Avatar answered Oct 02 '22 21:10

Dhwani Katagade