javascript Joi 验证多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26509551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:03:18  来源:igfitidea点击:

Joi validation multiple conditions

javascripthapijsjoi

提问by user2468170

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 cfield definition so that it is required when:

但我想在c字段定义上添加一个条件,以便在以下情况下需要它:

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

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

How can I do that?

我怎样才能做到这一点?

回答by Gergo Erdosi

You can concatenate two whenrules:

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

回答by Simian

The answer by Gergo Erdosi didn't work with Joi 14.3.0, this resulted in an ORcondition:

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

a === 'avalue' || b === 'bvalue'

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

这导致 a === 'avalue' && b === 'bvalue'