You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Yup实现关联字段双向校验?遇TypeError报错求助

解决Yup双向关联校验报错及实现正确逻辑

报错原因分析

  1. Schema实例重复创建:在when的then/otherwise中直接新建yup.date()/yup.string()实例,而非基于原Schema链式扩展,导致Yup内部branch函数调用失败。
  2. 日期字段判断错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:42:51