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.
You may need to create your own custom validator;
expressValidator = require('express-validator');
validator = require('validator');
app.use(expressValidator({
customValidators: {
isArray: function(value) {
return Array.isArray(value);
},
notEmpty: function(array) {
return array.length > 0;
}
gte: function(param, num) {
return param >= num;
}
}
}));
req.checkBody('category', 'category cannot be empty').isArray().notEmpty();