如何在快速验证器中比较数组的整数元素?

How can I compare integer elements of an array in express validator?

我有一个 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);
    }
];

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

您可以使用 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 选项对我不起作用

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

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