【问题标题】:Yup conditional object validation not working是的,条件对象验证不起作用
【发布时间】:2020-07-30 05:19:39
【问题描述】:

我正在尝试为一个对象定义一个 Yup 验证 - 如果定义的兄弟设置为 true,则应该需要类型为 object 的字段,否则不需要

例子:

const { object, string, number, date, boolean } = require('yup')

const contactSchema = object({
  isBig: boolean(),
  count: number()
    .when('isBig', {
      is: true, // alternatively: (val) => val == true
      then: number().min(5),
      otherwise: number().min(0),
    }),
 complexOne: object({
    simpleOne: string(),
 })
 .when('isBig', {
     is: true,
     then: object().required(),
     otherwise: object(),
 })
})

传入验证的对象:

{
    isBig: true,
    count: -1,
}

如您所见,我故意不传递complexOne,因为我希望 Yup 显示错误。 count 的验证工作正常 - 如果值小于 0 并且 isBig 设置为 true,Yup 将正确显示错误留言ValidationError: count must be greater than or equal to 5

不幸的是,它完全忽略了 complexOne 字段的条件验证集。要么是的不支持对象类型的when,要么我做错了。

感谢您的帮助

【问题讨论】:

    标签: javascript yup


    【解决方案1】:

    您必须将 strict 选项设置为 true 才能仅验证对象,并跳过任何强制或转换:

    contactSchema.validate(contact, { strict: true })
    .then(obj => {
      console.log(obj)
    }, err => {
      console.log(err.message)
    })
    

    演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多