joi
joi copied to clipboard
Add isPresent option to object dependencies
I needed a feature such as in this StackOverflow question.
When you have a schema such as:
const schema = Joi.object({
a: Joi.string().default(() => null),
b: Joi.string().default(() => null)
}).oxor('a', 'b');
You may want schema.validate({})
to pass, however, currently this will fail because the oxor
rule will resolve a
and b
to null
, and the current check is against undefined
.
This PR adds a new option, isPresent
, that allows for something like:
const schema = Joi.object({
a: Joi.string().default(() => null),
b: Joi.string().default(() => null)
}).oxor('a', 'b', { isPresent: (resolved) => resolved !== undefined && resolved !== null });
In this case, the oxor
(or any of the other dependency options, such as xor
or and
) will accept undefined
and null
values as empty.
Hi,
Just wondering, do you actually need a function for that? I mean, it looks more flexible, but it could as well be a flag that also checks for null values. I don't know if presence can or should be defined by any other keyword.
I prefer the extra flexibility of a function, but i could go either way really... If this ever gets reviewed that is 😅
I've changed a bit the implementation but it should be good now. Thanks for the PR!