joi icon indicating copy to clipboard operation
joi copied to clipboard

Add isPresent option to object dependencies

Open perrin4869 opened this issue 2 years ago • 2 comments

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.

perrin4869 avatar Apr 05 '22 15:04 perrin4869

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.

Marsup avatar Aug 20 '22 17:08 Marsup

I prefer the extra flexibility of a function, but i could go either way really... If this ever gets reviewed that is 😅

perrin4869 avatar Aug 20 '22 18:08 perrin4869

I've changed a bit the implementation but it should be good now. Thanks for the PR!

Marsup avatar Oct 22 '22 11:10 Marsup