Reputation: 13119
I have union type PaymentTerm
:
type PaymentTerm =
| { type: 'AdvancePayment' }
| { type: 'PaymentGoal'; netPaymentDays: number }
I want to validate it using Joi.alternatives
:
Joi.object({
type: Joi.string().required().valid('AdvancePayment')
}),
Joi.object({
type: Joi.string().required().valid('PaymentGoal'),
netPaymentDays: Joi.number().required().messages({
'any.required': '{{#label}} is required'
})
})
)
const { error, value } = schema.validate({
type: 'PaymentGoal'
})
Now I would expect to get "netPaymentDays" is required
but I get "value" does not match any of the allowed types
.
How can I get the "nested" errors instead of the generic ones for the alternatives?
Upvotes: 2
Views: 2075
Reputation: 5738
You've mentioned the correct way to resolve this but I can't see it being used in your example.
I want to validate it using
Joi.alternatives
A possible solution for your schema would be:
Joi.object().keys({
type: Joi.string().valid('AdvancePayment', 'PaymentGoal').required(),
netPaymentDays: Joi.alternatives().conditional('type', {
is: 'PaymentGoal',
then: Joi.number().required(),
otherwise: Joi.forbidden()
})
});
Upvotes: 3