Search code examples
javascriptjoi

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.


Solution

  • 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.