Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi validation: or() and xor() condition depending upon field value

I have a schema that looks like this:

{
   a: joi.boolean(),
   b: joi.object(),
   c: joi.object()
}

Depending upon the value of field a = false, I want fields b or c to exist. If a is false, I want a xor condition on fields b and c.

I tried using when but I'm unable to find a perfect solution.

like image 500
Darshani Audhish Avatar asked Jan 30 '26 16:01

Darshani Audhish


1 Answers

I could find one possible solution for the problem. Here's it.

Joi.object({
 a: Joi.boolean(),
 b: Joi.object(),
 c: Joi.object()
})
.required()
.when( Joi.object({a:false}).unknown(), {
 then: Joi.object().or('a','b'),
 otherwise: Joi.object().oxor('a','b')
})

This worked for me.

like image 167
Darshani Audhish Avatar answered Feb 01 '26 06:02

Darshani Audhish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!