Reputation: 325
I'm trying to validate a POST request where the title
can be a String or an Object with language keys and values. Example:
{
title: 'Chicken',
...
}
//OR
{
title: {
en_US: 'Chicken',
de_DE: 'Hähnchen'
}
...
}
And with Joi I'm trying to validate like so:
{
title: Joi.any().when('title', {
is: Joi.string(),
then: Joi.string().required(),
otherwise: Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
}).required()
}),
...
}
However, when I try to validate I get the error AssertionError [ERR_ASSERTION]: Item cannot come after itself: title(title)
Is there a way to use when
with the same field?
Upvotes: 9
Views: 14346
Reputation: 5738
Take a look at using .alternatives()
rather than .when()
for this situation. .when()
is better used when the value of your key is dependant on another key's value within the same object. In your scenario, we've only got the one key to worry about.
A possible solution using .alternatives()
could look like:
Joi.object().keys({
title: Joi.alternatives(
Joi.string(),
Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
})
).required()
})
Upvotes: 29