首页 > 解决方案 > 条件验证是的 - 任何一个字段都是必需的(错误:未捕获的错误:循环依赖,节点为:“b”。)

问题描述

在我的应用程序中,我使用的是 Yup 验证。我遇到了一个场景,我至少需要三个字段(字符串)中的一个。我试过使用下面的代码,但它抛出Uncaught Error: Cyclic dependency, the node was: "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.

标签: formikyup

解决方案


我发现你可以使用lazyYup 中的构造来做到这一点。

懒惰的参考: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']])```

推荐阅读