FLC
FLC

Reputation: 895

Is it possible to require at least one field from a set of defined fields?

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.

Upvotes: 18

Views: 11887

Answers (2)

FLC
FLC

Reputation: 895

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.

Upvotes: 34

Ankh
Ankh

Reputation: 5718

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.

Upvotes: 41

Related Questions