Joi validating multiple conditions

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 to the field definition c

so that it is required when:

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

How can i do this?

+4


source to share


2 answers


You can combine two rules when

:



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

      

+10


source


Jergo Erdosi's answer didn't work for me with Joi 14.3.0

, it gave me a condition OR

:

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

      

It gave me a === 'avalue' AND b === 'bvalue'

0


source







All Articles