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.
not() Negates the result of the next validator.
The isArray() method returns true if an object is an array, otherwise false .
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.
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.
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);
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