繁体   English   中英

Joi 验证多个条件

[英]Joi validation multiple conditions

我有以下架构:

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'

我怎样才能做到这一点?

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

Gergo Erdosi 的回答不适用于 Joi 14.3.0 ,这导致了OR条件:

a === 'avalue' || 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' && b === 'bvalue'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM