存在数组元素时的 Joi 验证

Joi validations when there is an array elements

我想使用 Joi 实现以下验证。

我的架构:

const schema = Joi.object({
   createdDate: Joi.string().required(),
   futureDate: Joi.string().allow("").optional(),
   Events: Joi.array().items({
      status: Joi.string().required(),
      type: Joi.string().required()       
   })
});

我的输入请求是这样的。我正在使用上述架构和验证来验证以下请求。如果 Events.type == "XYZ"futureDate 是必需的,否则它是可选的。

   {
            "createdDate": "2021-02-02T00:00:00",           
            "futureDate": "2021-02-02T00:00:00",
            "Events": [
                {
                    "status": "P",
                    "type": "ABC"
                },
                {
                    "status": "S",
                    "type": "XYZ"
                }            
                
            ]
   }

你必须合并 .when with .has:

Joi.object({
   createdDate: Joi.string().required(),
   futureDate: Joi.string().allow("").optional(),
   Events: Joi.array().items({
      status: Joi.string().required(),
      type: Joi.string().required()       
   })
}).when(Joi.object({ Events: Joi.array().items({
    status: Joi.string().required(),
    type: Joi.string().required()       
  })
  .required()
  .has(Joi.object({ status: Joi.string(), type: 'XYZ' })) }).unknown(), {
       then: Joi.object({ futureDate: Joi.required() })
})

我们这里“说”的是,当Events数组存在且至少包含一个元素为type: 'XYZ'时,则需要futureDate