Joi验证多个条件

时间:2014-10-22 14:13:42

标签: javascript hapijs joi

我有以下架构:

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

但我想在c字段定义中添加条件,以便在以下情况下使用:

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

我该怎么做?

2 个答案:

答案 0 :(得分:17)

您可以连接两个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() }))
};

答案 1 :(得分:2)

Gergo Erdosi的回答不适用于Joi 14.3.0,这给了我一个OR条件:

a === 'avalue' OR b === 'bvalue'

以下对我有用:

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

这给了我a === 'avalue' AND b === 'bvalue'