Search code examples
javascriptexpress-validator

How can I make ExpressValidator validate empty array OR contents of array


I have an array that passes through my validator, which currently looks like this:

expressValidator.body('animals.*').custom(checkAnimal).withMessage('Must provide an array containing valid animals')

So if I feed it ['goat','lemming','ocelot'] it will pass, and ['goat','lemming','Buick'] will fail on the last element.

However... an EMPTY array ("[]") is also valid, and I can't figure out how to write that validator


Solution

  • Found it:

    expressValidator.oneOf([
      expressValidator.body('animals').isArray()
        .withMessage('animals must be an array')
      expressValidator.body('animals.*').custom(checkAnimal)
        .withMessage('Must provide an array containing valid animals')
    ])