Express Joi使用when条件验证对象数组

Express Joi使用when条件验证对象数组,express,nodes,hapijs,joi,Express,Nodes,Hapijs,Joi,首先,抱歉英语不好 我找不到任何关于这个的文件 我想做什么 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. } ] }; 我的工作模式(未工作) 此代码工作不

首先,抱歉英语不好

我找不到任何关于这个的文件

我想做什么

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.
    }
  ]
};
我的工作模式(未工作)

此代码工作不正常。 当类型为“c”时,将通过验证


如何修复此问题?

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

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()
            }))
        })
})

oops,我的版本是16.1.8
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()
            }))
        })
})