Home > Net >  Validate an array property only if another property inside the same object is true with express-vali
Validate an array property only if another property inside the same object is true with express-vali

Time:12-31

I'm using express-validator to validate the requests to my express application and I have one endpoint that receives one object in which one of the properties is an array of objects. It looks like this below.

{
    "propA": "",
    "propB": "",
    "items": [
         {
              "enabled": true,
              "name": "",
              "icon": "",
         }
    ]
}

I want to be able to set the name and icon as required only if the enabled property is set to true.

I tried to do something like this, but I doesn't work as expected.

  body("items").isArray().withMessage("Items format is invalid"),
  body("items.*.enabled").isBoolean(),
  body("items.*.name").if(body("items.*.enabled")).notEmpty().bail(),
  body("items.*.icon").if(body("items.*.enabled")).notEmpty().bail()

CodePudding user response:

Apparently, it's not possible to do this in express-validator's version I'm using (6.12.1). I had to write a custom function and use validator.js functions (which is used by express-validator) manually.

https://github.com/express-validator/express-validator/issues/1126

Maintainers are planning to improve this on version 7.0.0.

  • Related