Search code examples
javascriptjoihapi

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.


Solution

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