Joi conditional validation of a key and its valid values based on another key value

293 Views Asked by At

I want joi validation for a key values in such a way that it depends on the value of another key i.e type.

I have an object which looks like:

const validValues = {
    banana:['001','002','003'],
    apple: ['111','122','133']
}

Here, the schema looks like:

const schema = Joi.object({
  type: Joi.string()
    .valid(...Object.keys(validValues))
    .required()
  })})

I want to validate values here in such a way that if 'banana' is given as type then the values should only accept ['001','002','003'] and if 'apple' is given as type then the acceptable values is ['111','122','133']. Also, the values is optional as well.

My payload:

{
    "type": "banana",
    "values": ["cvf"]
}

This payload should give an error because the the values dont map to the type.

1

There are 1 best solutions below

2
B-saal Giri On

In the above condition, I think we can easily check the type property using the valid() method. Regarding the values check, we can use the switch option. switch is useful when we have multiple value to check for the same key.

Joi.object({
  type: Joi.string().valid('banana', 'apple').required(),
  values: Joi.string().when('type', {
    switch: [
      { is: 'banana', then: Joi.valid('001','002','003') },
      { is: 'apple', then: Joi.valid('111','122','133') }
    ],
    otherwise: Joi.forbidden()
  })
})

You can check this result realtime in the given website by copy pasting the above rules. Joi Tester

Note: Since the Joi Tester does not support the JS code to test. I have hard coded the values like apple, banana and their values, rather than using JS code like Object.keys(validValues)