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

Viewed 2040

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.

2 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.

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

I think you are looking for something like this. Joi.when()

Related