我创建了一个初始值类似于
的formik对象{customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}}
我如何为这个对象编写一个条件 yup 验证模式,这样如果 customerDetails 的 id 存在,则不需要姓名和手机号码,但如果 id 不存在则需要。
我试过这样的事情:
const validationSchema = Yup.object().shape({
customerDetails: Yup.object().shape({
id: Yup.string(),
firstName: Yup.string().when('id', {
is: (value: string) => !Boolean(value),
then: Yup.string().required("Required")
}),
})
})
但是我收到这个错误:
No overload matches this call.
Overload 1 of 4, '(keys: string | string[], builder: ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>): StringSchema<string, AnyObject, undefined, "">', gave the following error.
Argument of type '{ is: (value: string) => boolean; then: Yup.StringSchema<string, Yup.AnyObject, undefined, "">; }' is not assignable to parameter of type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.
Object literal may only specify known properties, and 'is' does not exist in type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.
Overload 2 of 4, '(keys: string | string[], options: ConditionConfig<StringSchema<string, AnyObject, undefined, "">>): StringSchema<string, AnyObject, undefined, "">', gave the following error.
Type 'StringSchema<string, AnyObject, undefined, "">' is not assignable to type '(schema: StringSchema<string, AnyObject, undefined, "">) => ISchema<any, any, any, any>'.
Type 'StringSchema<string, AnyObject, undefined, "">' provides no match for the signature '(schema: StringSchema<string, AnyObject, undefined, "">): ISchema<any, any, any, any>'.ts(2769)
index.d.ts(296, 5): The expected type comes from property 'then' which is declared here on type 'ConditionConfig<StringSchema<string, AnyObject, undefined, "">>'
使用 Yup 1.x,我会这样写表达式:
firstName: Yup.string().default<string | null>(null)
.when(([], schema) =>
!id ? schema.required("Required") : schema.nullable()
)
请注意,文档建议像这样向数组添加依赖字段
.when(([id], schema) =>
但是我在使用它时遇到了一些验证状态没有更新的问题,因此我把它留在这里了。
如果您的要求不同于将
null
作为默认值,请相应地更改default
。