37

I have the following schema:

var testSchema = Joi.object().keys({
    a: Joi.string(), 
    b: Joi.string(), 
    c: Joi.string().when('a', {'is': 'avalue', then: Joi.string().required()})
});

but I would like to add a condition on c field definition so that it is required when:

a == 'avalue' AND b=='bvalue'

How can I do that?

SaintLike
  • 9,119
  • 11
  • 39
  • 69
user2468170
  • 1,234
  • 2
  • 15
  • 19

2 Answers2

45

You can concatenate two when rules:

var schema = {
    a: Joi.string(),
    b: Joi.string(),
    c: Joi.string().when('a', { is: 'avalue', then: Joi.string().required() }).concat(Joi.string().when('b', { is: 'bvalue', then: Joi.string().required() }))
};
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
28

The answer by Gergo Erdosi didn't work with Joi 14.3.0, this resulted in an OR condition:

a === 'avalue' || b === 'bvalue'

The following worked for me:

var schema = {
  a: Joi.string(),
  b: Joi.string(),
  c: Joi.string().when(
    'a', {
      is: 'avalue',
      then: Joi.when(
        'b', {
          is: 'bvalue',
          then: Joi.string().required()
        }
      )
    }
  )
};

This results in a === 'avalue' && b === 'bvalue'

Simian
  • 814
  • 11
  • 21