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.
In the above condition, I think we can easily check the type property using the
valid()method. Regarding the values check, we can use theswitchoption.switchis useful when we havemultiplevalue to check for thesame key.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, bananaand their values, rather than using JS code like Object.keys(validValues)