Express validator for checking a parameter, which is an array

I use the express validator to check the POST data in my express application. I have a form in which there is a choice where the user can select several options:

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

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

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

Now in my Express application, I am trying to test it as follows:

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

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

+7
source share
2

, ;

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

, , , customValidator, , .

https://github.com/edgracilla/wallter

:

const halter = require('wallter').halter
const Builder = require('wallter').builder // validation schema builder

const builder = new Builder()

server.use(halter())

server.post('/test', function (req, res, next) {
    let validationSchema = builder.fresh()
      .addRule('category.*', 'required')
      .build()

    // validationSchema output:
    // { 'category.*': { required: { msg: 'Value for field \'category.*\' is required' } } }

    req.halt(validationSchema).then(result => {
        if (result.length) {
            res.send(400, result)
        } else {
            res.send(200)
        }

        return next()
    })
})

. repo README.md.

+1

All Articles