我在 ReactJS 应用程序中将 Yup 与 Formik 一起使用。
我有一堆字段,如果任何字段被填充,这些字段就会成为必需的。
幸运的是,Yup 提供了一个函数
when
来解决条件验证问题,但由于所有这些字段都是相互依赖的,Yup 无法开箱即用地处理它。
...authRepTwoFirstName: Yup.string().when(
[
"authRepTwoLastName",
"authRepTwoBusinessTitle",
"authRepTwoJobPosition",
"authRepTwoPhoneNumber",
"authRepTwoEmail"
],
authTwoValidationSchema
),
authRepTwoLastName: Yup.string().when(
[
"authRepTwoFirstName",
"authRepTwoBusinessTitle",
"authRepTwoJobPosition",
"authRepTwoPhoneNumber",
"authRepTwoEmail"
],
authTwoValidationSchema
),...
function authTwoValidationSchema(fields: string[], schema: Schema) {
return fields.some(field => field?.length)
? schema.required("All fields for auth rep two need to be filled if in use")
: schema.notRequired()
}
在上面的示例中,我收到错误
Cyclic dependency, node was:"authRepTwoLastName"
解决这个问题的好策略是什么?
对于任何有类似问题的人,spec中都有答案:
You can also prefix properties with $ to specify a property that is dependent on context passed in by validate() or cast instead of the input value.
我有两个相互依赖的字段,比如说 A 和 B。我遇到了同样的错误。我通过添加一个由这两个字段组成的数组来修复它(如下所示:['A','B'])。成功了。
{ ... A: Yup.string().when( ... ), B: Yup.string().when( ... ), ... }, ['A', 'B']
确保数组在 A 和 B 的父级之后传递,如下所示:
{ A: ..., B: ...}, ['A', 'B']