16

Given a definition like this:

const querySchema = joi.object({
  one: joi.string().min(1).max(255),
  two: joi.string().min(1).max(255),
  three: joi.string().min(1).max(255),
});

Is there a way to require at least one of those fields? I don't care which one.

Note: the solution provided for this SO question doesn't serve me as I have 7 fields and they may grow, so doing all the possible combinations is a no-go.

Couldn't find any methods in Joi API Reference that may be useful for this use case.

Any help is greatly appreciated.

Community
  • 1
  • 1
FLC
  • 786
  • 1
  • 6
  • 18

2 Answers2

37

If you really don't care which one is required then you could just ensure there is at least one key in the object by using object().min(1).

const querySchema = joi.object({
    one: joi.string().min(1).max(255),
    two: joi.string().min(1).max(255),
    three: joi.string().min(1).max(255),
}).min(1);

At least one key (one, two, three) must be required. Keys with names different to those three will be rejected.

Ankh
  • 5,478
  • 3
  • 36
  • 40
30

Found another way to do it besides the one suggested by @Ankh, was in documentation but I couldn't find it before:

const schema = joi.object({
   a: joi.number(),
   b: joi.number(),
}).or('a', 'b');

This method is good if one needs to require a specific set of keys, while @Ankh's is better when the requirement is exaclty as I this question title and you have many keys, so I'm choosing his answer over mine as the right one.

Just wanted to leave here another way to do it.

FLC
  • 786
  • 1
  • 6
  • 18