Reputation: 93
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?
Upvotes: 4
Views: 4458
Reputation: 2009
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)
})
})
})
Upvotes: 8
Reputation: 338
If you don't need Joi.ref
, this would still work with ...
referencing the parent's sibling, like about14sheep pointed out in their answer. I ended up doing something like this:
Joi.object({
a: Joi.string(),
b: Joi.object({
c: Joi.when('...a', {
is: 'foo',
then: Joi.number().valid(1),
otherwise: Joi.number().valid(2),
}),
}),
});
Upvotes: 0