条件验证是-必填字段(错误:未捕获错误:循环依赖,节点为:“ b”。)

时间:2020-08-04 15:13:33

标签: formik yup

在我的应用程序中,我正在使用Yup验证。我遇到的情况是,我至少需要三个field(String)之一。我尝试使用下面的代码,但是它抛出 Uncaught Error:循环依赖关系,该节点为:“ b”

a: yup.string().when(['b', 'c'], {
 is: (b, c) => !b && !c,
 then: yup.string().required()
}),
b: yup.string().when(['a', 'c'], {
 is: (a, c) => !a && !c,
 then: yup.string().required()
}),
c: yup.string().when(['a', 'b'], {
 is: (a, b) => !a && !b,
 then: yup.string().required()
})
}, [['a', 'b'], ['a', 'c'], ['b','c']])```

Any response or working code would be very helpful. Thanks in advance.

1 个答案:

答案 0 :(得分:0)

我发现您可以使用Yup中的lazy构造做到这一点。

参考懒惰:https://github.com/jquense/yup#yuplazyvalue-any--schema-lazy

创建一个在验证/广播时评估的架构。对于创建多态字段和数组的树之类的递归模式很有用。

示例:

a: yup.lazy(() => yup.string().when(['b', 'c'], {
 is: (b, c) => !b && !c,
 then: yup.string().required()
})),
b: yup.lazy(() => yup.string().when(['a', 'c'], {
 is: (a, c) => !a && !c,
 then: yup.string().required()
})),
c: yup.lazy(() => yup.string().when(['a', 'b'], {
 is: (a, b) => !a && !b,
 then: yup.string().required()
}))
}, [['a', 'b'], ['a', 'c'], ['b','c']])```