The documentation is not explicit about what we can test in the 'is' key of Joi.when(). How can I say:
1 - IF ref IS 'Hello' OR 'World' OR 'Foo' THEN ...
2 - IF ref IS NOT 'Hello' AND 'World' THEN ...
3 - IF ref IS IN ['HAPI', 'EXPRESS'] THEN ...
4 - IF ref IS NOT IN ['HAPI', 'EXPRESS'] THEN ...
5 - IF ref IS {...} THEN ...
It would have been easier to understand the doc if there where additional keys like
- IS NOT ...
- IN [...]
- NOT IN [...]
Anything that you put in there will be converted to a joi schema for simplicity, but you can provide one directly if you have more advanced needs. The documentation is indeed poor on this point, documentation PRs always welcome.
OK, please let's take one case.
schema = Joi.object().keys({
type: Joi.string().valid(['movie', 'documentary', 'advert', 'Clip', 'tv-serie']),
duration: Joi.number().when('type', {
is: 'anything-except-tv-serie',
then: Joi.required()
})
});
How can I implement 'anything-except-tv-serie' ?
As a work arround I can try this:
{
is: 'tv-serie',
otherwise: Joi.required()
}
But I hope there is a better way. What if I want anything except TV-Serie and Movie ?
Your way works and there's nothing wrong with using only otherwise.
It's translated to :
{ is: Joi.only('tv-serie'), otherwise: Joi.required() }
You could also write it like :
{ is: Joi.not('tv-serie'), then: Joi.required() }
Then more complex cases come naturally as :
{ is: Joi.not(['tv-serie', 'movie']), then: Joi.required() }
// or
{ is: Joi.only(['tv-serie', 'movie']), otherwise: Joi.required() }
Reason about it like any other schema.
Great, just what I was looking for. I got you now when you said "Anything that you put in there will be converted to a joi schema...".
Thanks.
I'll keep this one opened in case someone wants to help with the docs.
OK, sure that docs will help a lot. I will propose something.
Most helpful comment
Your way works and there's nothing wrong with using only
otherwise.It's translated to :
You could also write it like :
Then more complex cases come naturally as :
Reason about it like any other schema.