【问题标题】:Joi nested whenJoi 嵌套时
【发布时间】:2021-09-28 14:19:37
【问题描述】:
const schema = {
    a: Joi.any(),
    b: Joi
      .boolean()
      .default(false),
    c: Joi
      .boolean()
      .default(false)
}

如何修复上述 Joi 架构以匹配以下规则

  • bc 之一可以同时是true
  • bctrue 时,aforbidden 否则arequired

【问题讨论】:

    标签: javascript joi


    【解决方案1】:
    Joi.object( {
      a: Joi
          .boolean()
          .default(false),
      b: Joi
          .boolean()
          .default(false),
      c: Joi.string().when(
        'a', {
          is: false,
          then: Joi.when(
            'b', {
              is: false,
              then: Joi.string().required()
            }
          )
        }
      ),
    })
    

    我在提问之前尝试了嵌套when,但由于规则的顺序,它以前不起作用

    Joi.object( {
      c: Joi.string().when(
        'a', {
          is: false,
          then: Joi.when(
            'b', {
              is: false,
              then: Joi.string().required()
            }
          )
        }
      ),
      a: Joi
          .boolean()
          .default(false),
      b: Joi
          .boolean()
          .default(false),
    })
    

    when 正在检查时,第二个架构中的 default 值未设置,因此如果您验证一个空对象 {},则第一个架构有 Validation Error: "c" is required 错误,而第二个架构有 Passed 987654330@

    我在这里打开了一个问题https://github.com/sideway/joi/issues/2683

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 2021-09-06
      • 2020-02-14
      • 2019-03-23
      • 2018-02-27
      • 2018-02-20
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多