Condition Validation Yup- Any one field is required (Error: Uncaught Error: Cyclic dependency, the node was: "b".)

Condition Validation Yup- Any one field is required (Error: Uncaught Error: Cyclic dependency, the node was: "b".)

在我的应用程序中,我使用的是 Yup 验证。我遇到了一个场景,我至少需要三个字段(字符串)中的一个。我试过使用下面的代码,但它抛出 未捕获错误:循环依赖,节点是:“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.

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

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

Creates a schema that is evaluated at validation/cast time. Useful for creating recursive schema like Trees, for polymorphic fields and arrays.

示例:

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']])```