Search code examples
arraysnode.jsexpressvalidationexpress-validator

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


I have an express validator for a 2-length integer array that looks like this.

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

I would like to check that the second integer of the array is bigger than the first one. How can I do that?


Solution

  • You can use a custom validator in order to have access to the array elements

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

    By the way, min and max options for the isArray() method didn't work for me