简体   繁体   English

express-validator 验证数组参数

[英]express-validator to validate parameter which is an array

I am using express-validator to validate POST data in my express application.我正在使用express-validator来验证我的 express 应用程序中的 POST 数据。 I have a form which has a select where in user can select multiple options:我有一个表格,其中有一个 select,用户可以在其中 select 多个选项:

<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:如果我 select 多个值,提交表单后的有效负载会向我显示:

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

Now, in my Express application I try to validate it like this:现在,在我的 Express 应用程序中,我尝试像这样验证它:

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

But, even after I send multiple values I always get the error - category cannot be empty .但是,即使在我发送了多个值之后,我总是会收到错误 - category cannot be empty If I print my variable as req.body.category[0] - I get the data.如果我将我的变量打印为req.body.category[0] - 我得到了数据。 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();

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);

Answering a bit late but hope this might help somebody.回答有点晚,但希望这可能对某人有所帮助。

If you are using express-validator , You can pass minimum / maximum length option to check whether Array is empty or exceeds a certain limit如果您使用express-validator ,您可以通过最小/最大长度选项来检查 Array 是否为空或超过某个限制

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

If you are using schema, you can do it this way:如果您使用的是架构,则可以这样做:

const schema = {
  someArray: { isArray: true, notEmpty: true }
};

This maybe a bit late but for others who wants a clean solution without using the customValidator , I created a validator that can dig up to the deepest array and validate its content.这可能有点晚了,但对于其他想要一个干净的解决方案而不使用customValidator ,我创建了一个验证器,可以挖掘到最深的数组并验证其内容。

https://github.com/edgracilla/wallter https://github.com/edgracilla/wallter

In your case validation would be:在您的情况下,验证将是:

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()
    })
})

Error message can be override in builder initialization.错误消息可以在构建器初始化中被覆盖。 Check the repo README.md for an in depth usage.检查 repo README.md以获取深入的用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM