我的数据结构如下所示:
{
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抛出一个预期的错误。我遗漏了什么?
发布于 2019-04-23 19:56:54
when()只能访问同一级别的属性。来自文献资料
mixed.when(键: string 000-Array,builder: object回(值,模式)=>模式):模式 根据同级或同级子字段调整架构。您可以提供一个对象文本,其中键是value或matcher函数,然后为失败条件提供真正的架构和/或其他方式。
这就是为什么您的第二个示例可以工作(因为bar和foo是兄弟)。一个可能的解决方案是重新排列您的数据,以便foo和baz是兄弟。
至少有关于Yup's Github的一个问题,作者建议通过Yup的上下文参数传递数据,但我认为使用Formik和validationSchema支柱是不可能的,假设这就是您所使用的。
https://stackoverflow.com/questions/55818053
复制相似问题