Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express-validator to validate parameter which is an array

I am using express-validator to validate POST data in my express application. I have a form which has a select where in user can select multiple options:

<select name="category" multiple id="category">
    <option value="1">category 1 </option>
    .......
</select>

The payload after submitting form shows me this if I select multiple values:

...&category=1&category=2&....

Now, in my Express application I try to validate it like this:

req.checkBody('category', 'category cannot be empty').notEmpty();

But, even after I send multiple values I always get the error - category cannot be empty. If I print my variable as req.body.category[0] - I get the data. But, somehow not able to understand the way I need to pass this to my validator.

like image 597
pankaj Avatar asked May 20 '16 06:05

pankaj


People also ask

What is not () in Express validator?

not() Negates the result of the next validator.

How do you validate an array in Javascript?

The isArray() method returns true if an object is an array, otherwise false .

What is checkFalsy in Express validator?

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.

Which is better express validator or Joi?

Express-validator So by definition, we can say that: 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.


1 Answers

Try this:

router.post('/your-url', 
      [
        check('category').custom((options, { req, location, path }) => {
            if (typeof category === 'object' && category && Array.isArray(category) && category.length) {
              return true;
            } else {
              return false;
            }
          })
    ],
    controller.fn);
like image 136
Sanjay Kumar N S Avatar answered Sep 29 '22 14:09

Sanjay Kumar N S