【问题标题】:Validating nested objects by making child object value optional based on parent value using JOI通过使用 JOI 根据父值使子对象值可选来验证嵌套对象
【发布时间】:2021-07-21 16:32:09
【问题描述】:

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

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 的形式出现。下面的代码应该可以解决问题,但由于某种原因,它总是“需要” c.d !!

任何指针?

【问题讨论】:

    标签: javascript validation joi


    【解决方案1】:

    您是否考虑过将您的 .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,因为它已经是你的默认值了。

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2020-03-14
      • 2016-02-19
      • 2020-12-02
      • 2019-04-30
      • 2017-08-05
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多