Joi验证多个条件

use*_*170 14 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()})
});
Run Code Online (Sandbox Code Playgroud)

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

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

我怎样才能做到这一点?

Ger*_*osi 23

您可以连接两个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() }))
};
Run Code Online (Sandbox Code Playgroud)


Sim*_*ian 5

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()
        }
      )
    }
  )
};
Run Code Online (Sandbox Code Playgroud)

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