Search code examples
node.jsvalidationnpmbackendjoi

Joi nested object operations


I have a Joi schema of type:

const schema = Joi.object().keys({
  a: Joi.string(),
  b: Joi.string(),
  c: Joi.string()
})

Now, I want to add a condition that if a is not present then both b and c should be present. I know there are operations like object.and() and object.or() but I am not sure how to use these in my case i.e. a or (b and c). Thanks!


Solution

  • You'll want to use Joi's alternatives and conditional functionality, which you can read about in the documentation

    const schema = {
        a: Joi.string(),
        b: Joi.when('a', { is: !Joi.exist(), then: Joi.string().required() }),
        c: Joi.when('a', { is: !Joi.exist(), then: Joi.string().required() }),
    };