通过使用 JOI 根据父值使子对象值可选来验证嵌套对象

Validating nested objects by making child object value optional based on parent value using JOI

我正在尝试验证以下内容:

import { showErrors } from "./utils";

const data = {
  a: "test",
  b: "test",
  c: {
     //  d: ["x", "y"]
  }
};

const dataSchema = Joi.object({
  a: Joi.string().optional(),
  b: Joi.string().optional(),
  c: Joi.object({
    d: Joi.array().items("x","y")
  }).when(Joi.object({
    a: Joi.exist(),
    b: Joi.exist()
  }), {
    then:Joi.object({
      'd': Joi.optional()
    }),
    otherwise: Joi.object({
      'd': Joi.required()
    })
    
  })
});

showErrors(dataSchema.validate(data));

想法是让 c.d 可选,同时 ab 都作为 strings 出现。下面的代码应该可以解决问题,但由于某种原因它总是 'requiring' c.d !!

有什么指点吗?

您是否考虑过将 .when 放在初始对象中而不是 c 对象中?

Joi.object({
  a: Joi.string(),
  b: Joi.string(),
  c: Joi.object({
   d: Joi.array().items("x","y")
  }),
}).when(Joi.object({ a: Joi.exist(), b: Joi.exist() }).unknown(), {
  then: Joi.object({ // this is optional
    c: Joi.object({
      d: Joi.optional()
    })
  }),
  otherwise: Joi.object({
    c: Joi.object({
      d: Joi.required()
    }).required()
  })
})

此外,您应该使用 unknow(),并且在 thenotherwise 中您必须指定 c.d 而不仅仅是 d.

如果需要,您可以删除 then,因为它已经是您的默认值。