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

Yup非嵌套对象条件校验:otherReasonChangeJob依赖必填规则实现

Yup表单验证:仅当选择"Other"时必填其他原因字段

需求明确:仅当reasonChangeJob数组包含**"Other"**选项时,otherReasonChangeJob字段才需要填写;反之该字段可以留空。

以下是修正后的完整实现代码:

export const formikValues = {
  reasonChangeJob: [],
  otherReasonChangeJob: "",
}

export const questionnaireSchema = Yup.object({
  reasonChangeJob: Yup.array()
    .required("请选择至少一项离职原因")
    .min(1, "请选择至少一项离职原因"),
  otherReasonChangeJob: Yup.string().when(
    "reasonChangeJob",
    (reasonChangeJob) => {
      // 注意匹配选项的大小写,这里用"Other"对应需求中的值
      if (reasonChangeJob?.includes("Other")) {
        return Yup.string().required("请填写其他离职原因");
      }
      // 不满足条件时允许字段为空
      return Yup.string().nullable().notRequired();
    }
  )
});

关键修正与说明:

  • 原代码中的include是拼写错误,正确数组方法为includes
  • 添加可选链?.,避免reasonChangeJob为undefined时触发报错
  • 不满足条件时明确返回.nullable().notRequired(),确保字段在无需填写时不会触发验证逻辑
  • 替换模糊提示文本为更清晰的中文提示,优化用户体验
  • 注意选项值的大小写匹配:如果你的下拉选项是小写的"other",需将判断条件改为reasonChangeJob?.includes("other")

内容的提问来源于stack exchange,提问作者Muhammad Awais

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:20:43