Home > Software design >  Joi nested when validation
Joi nested when validation

Time:02-19

I am trying to validate a nested object conditionally based upon a value in the parent.

const schema = Joi.object({
    a: Joi.string(),
    b: Joi.object({
        c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Joi.number().valid(2) }),
    }),
});

const obj = {
    a: 'foo',
    b: {
        c: 2,
    },
};

In this example, I want to get an error that c must be 1, but the validation passes. I've tried with and without references, but I clearly must be misunderstanding something fundamental about how Joi works. Any help?

CodePudding user response:

you need one more . in your Joi.ref() call. .. will go up to the parent tree, then another dot to signify the property. So for your case it would go to the parent .. then get the a property parent.a

Using the Joi playground this worked for me:

Joi.object({
    a: Joi.string(),
    b: Joi.object({
        c: Joi.when(Joi.ref('...a'), {is: 'foo', then: Joi.number().valid(1), otherwise: Joi.number().valid(2)})
    })
})
  • Related