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 values.
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'
})
What you describe sounds like an or
constraint.
...a relationship between keys where one of the peers is required (and more than one is allowed)
The following schema would work:
joi.object().keys({
type: joi.string().valid('val1', 'val2'),
from: joi.string()
}).or('type', 'from');