【发布时间】: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