如何用Yup实现关联字段双向校验?遇TypeError报错求助
解决Yup双向关联校验报错及实现正确逻辑
报错原因分析
- Schema实例重复创建:在
when的then/otherwise中直接新建yup.date()/yup.string()实例,而非基于原Schema链式扩展,导致Yup内部branch函数调用失败。 - 日期字段判断错误:
termination_date是Date类型,不存在length属性,原代码中termination_date.length > 0的判断完全无效。
修正后的校验代码
const agentHistorySchema = yup.object().shape( { termination_date: yup.date().when("reason_for_termination", { is: (reason) => reason?.trim().length > 0, // 检查字符串非空(去除空格) then: (schema) => schema.required("请填写终止日期"), otherwise: (schema) => schema.nullable(), // 允许为空 }), reason_for_termination: yup.string().when("termination_date", { is: (date) => date != null, // 检查日期字段已填写 then: (schema) => schema.required("请填写终止原因"), otherwise: (schema) => schema.nullable(), // 允许为空 }), }, [["termination_date", "reason_for_termination"]] // 声明双向依赖,确保互相触发校验 );
关键修改说明
- 链式扩展Schema:在
then/otherwise中接收原Schema实例作为参数,直接调用required()或nullable()扩展,避免重复创建新实例。 - 修正字段判断逻辑:
- 字符串字段
reason_for_termination:用reason?.trim().length > 0判断非空(包含去除空格的场景); - 日期字段
termination_date:用date != null判断是否已填写(Date类型只需检查是否存在)。
- 字符串字段
- 保留双向依赖数组:
[["termination_date", "reason_for_termination"]]告诉Yup这两个字段互相依赖,修改其中一个时会触发另一个的校验。
校验逻辑验证
- 仅填写
termination_date:reason_for_termination会触发必填提示; - 仅填写
reason_for_termination:termination_date会触发必填提示; - 两者都填写或都不填写:校验通过。
内容的提问来源于stack exchange,提问作者Alex Aung
相关产品推荐
相关产品推荐

