Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

joi

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.

like image 716
FLC Avatar asked Mar 29 '17 20:03

FLC


1 Answers

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.

like image 129
Ankh Avatar answered Sep 22 '22 20:09

Ankh