express-validator验证作为数组的参数

pan*_*kaj 7 node.js express

我正在使用express-validator来验证我的快速应用程序中的POST数据.我有一个表单,其中有一个选择,在用户可以选择多个选项:

<select name="category" multiple id="category">
    <option value="1">category 1 </option>
    .......
</select>
Run Code Online (Sandbox Code Playgroud)

如果我选择多个值,提交表单后的有效负载会显示此信息:

...&category=1&category=2&....
Run Code Online (Sandbox Code Playgroud)

现在,在我的Express应用程序中,我尝试像这样验证它:

req.checkBody('category', 'category cannot be empty').notEmpty();
Run Code Online (Sandbox Code Playgroud)

但是,即使我发送多个值后,我总是得到错误 - category cannot be empty.如果我打印我的变量req.body.category[0]- 我得到数据.但是,不知何故无法理解我需要将其传递给验证器的方式.

ero*_*a84 11

您可能需要创建自己的自定义验证器;

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();
Run Code Online (Sandbox Code Playgroud)


adn*_*uja 6

回答有点晚但希望这可以帮助别人。

如果您使用express-validator,您可以通过最小/最大长度选项来检查数组是否为空或超过一定限制

req.checkBody('category', 'category cannot be empty').isArray({ min: 1, max: 10 });