【问题标题】:How can I compare integer elements of an array in express validator?如何在快速验证器中比较数组的整数元素?
【发布时间】:2020-08-07 21:25:23
【问题描述】:

我有一个 2 长度整数数组的快速验证器,看起来像这样。

exports.createItem = 
    check("times").exists()
        .withMessage('MISSING').isArray({min: 2, max: 2})
        .withMessage('err'),
    check("times.*").not()
        .isString().isInt(),
    (req,res, next) =>
    {
        validationResult(req,res,next);
    }
];

我想检查数组的第二个整数是否大于第一个整数。我该怎么做?

【问题讨论】:

  • 是否可以在代码中进行此验证?不使用 express-validator?
  • 我更喜欢 express 验证器,因为它已经在项目中使用了。

标签: arrays node.js express validation express-validator


【解决方案1】:

As dimitris tseggenes said 您可以使用自定义验证器来访问数组元素,我可以添加我的解决方案来遍历数组,在这种情况下是对象,并能够验证其属性之一

body("array")
    .optional()
    .custom((value) => {
        value.forEach(el => {
            if (el.uid == 0) throw new Error('The el is required');
            return true;
        });
        return true;
    });

【讨论】:

    【解决方案2】:

    您可以使用custom validator 来访问数组元素

    check("times").exists().withMessage('MISSING')
        .isArray().withMessage('times is not array')
        .custom((value) => {
            if (!value.every(Number.isInteger)) throw new Error('Array does not contain Integers'); // check that contains Integers
            if (value.length !== 2) throw new Error('Not valid Array Length'); // check length
            if (value[0] > value[1]) throw new Error('First element array is bigger than second'); 
            return true;
        })
    

    顺便说一句,isArray() 方法的 minmax 选项对我不起作用

    【讨论】:

    • 是的,这正是我在阅读您的答案之前所做的,它确实有效。无论如何,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多