Anonymous
Anonymous

Reputation: 1990

Schema for optional conditions in Joi

Suppose I have an object like:

{
  a : 1,
  b : 2,
  c : 3,
  d : 4
}

At least 1 of pair out of [a,b], [a,c], [d] should have validation passed(have correct values).

Assume all values are numbers.

How can I create Joi schema for it.

Upvotes: 3

Views: 841

Answers (2)

Wilfred Springer
Wilfred Springer

Reputation: 10927

Be careful with using Joi.number(). It will also consider '3' to be valid — without actually turning it into the number 3 if you're using Joi.assert. To avoid that, you should probably add the .strict() modifier.

See https://medium.com/east-pole/surprised-by-joi-35a3558eda30

Upvotes: 1

soltex
soltex

Reputation: 3551

You can use Joi.alternatives() and create a Joi schema like this:

Joi.alternatives().try(
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number().required(),
        c: Joi.number(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number(),
        c: Joi.number().required(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number(),
        b: Joi.number(),
        c: Joi.number(),
        d: Joi.number().required()
    }),
)

There is another alternative that uses .requiredKeys() and simplies the code above :

const JoiObjectKeys = {
    a: Joi.number(),
    b: Joi.number(),
    c: Joi.number(),
    d: Joi.number()
}

Joi.alternatives().try(
    Joi.object(JoiObjectKeys).requiredKeys('a', 'b'),
    Joi.object(JoiObjectKeys).requiredKeys('a', 'c'),
    Joi.object(JoiObjectKeys).requiredKeys('d'),
);

With this schema you will get this results:

{ a: 1 } > fails
{ b: 1 } > fails
{ c: 1 } > fails
{ a: 1, b: 1 } > passes
{ a: 1: c: 1 } > passes
{ d: 1 } > passes
{ d: 1, a: 1 } > passes

Upvotes: 2

Related Questions