Joi validation multiple conditions

2020-02-26 05:33发布

问题:

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?

回答1:

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() }))
};


回答2:

The answer by Gergo Erdosi didn't work for me with Joi 14.3.0, this gave me an ORcondition:

a === 'avalue' OR 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 gave me a === 'avalue' AND b === 'bvalue'