我的数据结构如下所示:
{
foo: true,
bar: {
baz: [{label: 'mario', url: 'https://nintendo.com'}]
}
}
我的yup
验证器看起来像这样:
const schema = yup.object().shape({
foo: yup.boolean(),
bar: yup.mixed().when('foo', {
is: true,
then: yup.object().shape({
baz: yup.array.of(
yup.object().shape({
label: yup.string.required(),
url: yup.url().required()
})
)
}),
otherwise: yup.object().nullable(true)
})
})
但验证不适用于bar.baz
;如果foo
是true
,如果没有给出带有所需对象的数组,bar就不会抛出错误。
如果我将bar
设置为以其他方式验证,请说:
bar: yup.mixed().when('foo', {
is: true,
then: yup.string().required()
otherwise: yup.string.nullable(true)
})
它按预期为bar
抛出一个错误。我错过了什么?
when()
只能访问同一级别的房产。来自the documentation:
mixed.when(keys:string | Array,builder:object |(value,schema)=> Schema):Schema
根据兄弟或兄弟子字段调整架构。您可以提供一个对象文字,其中键是值或匹配器函数,然后提供真实的模式和/或其他用于失败条件。
这就是为什么你的第二个例子有效(因为bar
和foo
是兄弟姐妹)。一种可能的解决方案是重新排列数据,以便foo
和baz
是兄弟姐妹。
至少有one issue on Yup's Github,作者建议通过Yup的上下文参数传递数据,但我不认为使用Formik和validationSchema
道具是可能的,假设你正在使用它。