【问题标题】:Joi validate array of objects with when conditionJoi 使用 when 条件验证对象数组
【发布时间】:2020-01-31 17:26:54
【问题描述】:

首先,抱歉英语不好。

我找不到任何关于此的文档。

我想做什么

const docs = {
  type: 'a', // ['a',' 'b', 'c'] is available.
  items: [
    {
      a: 123,
      b: 100 // => This value only available when type is 'a' or 'b'. otherwise, forbidden.
    }
  ]
};

我的 JOI 架构(不工作)

Joi.object({
  type: Joi.string().valid('a', 'b', 'c').required(),
  items: Joi.array()
    .items(
      Joi.object({
        a: Joi.number().required()
        b: Joi.number()
      })
    )
    .when('type', {
      is: Joi.string().valid('a', 'b'),
      then: Joi.array().items(Joi.object({ b: Joi.number().required() })),
      otherwise: Joi.array().items(Joi.object({ b: Joi.number().forbidden() }))
    })
})

此代码无法正常工作。 当 type 为 'c' 时,验证通过。

我该如何解决这个问题?

【问题讨论】:

  • 哎呀,我的版本是16.1.8

标签: express nodes hapijs joi


【解决方案1】:

您已将.items() 添加到items: Joi.array(),它会覆盖.when() 条件,请尝试使用

Joi.object({
    type: Joi.string().valid('a', 'b', 'c').required(),
    items: Joi.array()
        .when('type', {
            is: Joi.string().valid('a', 'b'),
            then: Joi.array().items(Joi.object({
                a: Joi.number().required(),
                b: Joi.number().required()
            })),
            otherwise: Joi.array().items(Joi.object({
                a: Joi.number().required()
            }))
        })
})

example

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2016-10-11
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    相关资源
    最近更新 更多