Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi nested when validation

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?

like image 350
ml-learner Avatar asked Sep 16 '25 00:09

ml-learner


1 Answers

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)
        })
    })
})
like image 112
about14sheep Avatar answered Sep 18 '25 16:09

about14sheep