I try to implement conditional validation with Joi. I have an endpoint that can accept either:
{
from: 'abc'
}
or
{
type: 'some-type'
}
If the type field isn't present, the from field is mandatory and if the from field isn't present, the type field is mandatory. The type can only accept a set of value.
I tried the following approach without success:
type: joi.alternatives().conditional('from', { is: joi.string().empty(), then: joi.string().required().valid('val1', 'val2'), otherwise: joi.optional() })
.messages({
'any.valid': 'type.not.supported.value',
'any.required': 'type.required'
}),
from: joi.alternatives().conditional('type', { is: joi.string().empty(), then: joi.required(), otherwise: joi.optional() })
.messages({
'any.valid': 'from.not.supported.value',
'any.required': 'from.required'
})
Thanks for your help! Thierry