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

添加report_to条件验证后Formik+Yup表单所有验证失效求助

解决Formik结合Yup时添加条件验证后所有规则失效的问题

问题原因

你添加的report_to字段条件验证存在两处写法问题,导致Yup的Schema验证逻辑异常,进而让Formik停止执行所有验证规则:

  1. otherwise分支仅使用Yup.string(),未明确标记字段为可选,导致Schema类型推断冲突;
  2. then和otherwise未采用函数式接收Schema参数的写法,不符合Yup的链式调用规范。

修复方案

修改employee_schema中report_to的条件验证规则,同时确保initialValues里position_id的初始值为数字类型:

修正后的Schema代码

import * as Yup from "yup";
const phoneRegExp = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/
export const employee_schema = Yup.object({
    branch_id: Yup.number().required("Please Select Branch"),
    position_id: Yup.number().required("Please Select Position"),
    first_name: Yup.string().required("First Name is required"),
    last_name: Yup.string().required("Last Name is required"),
    email: Yup.string().email().required("Please enter your email"),
    password: Yup.string().min(6).required("Please enter your password"),
    phone: Yup.string().matches(phoneRegExp ,'Phone number is not valid').required("Phone Number is required"),
    alternative_phone: Yup.string().matches(phoneRegExp, 'Phone number is not valid').required("Phone Number is required"),
    employment_type: Yup.number().required("Please Select Employement Type"),
    department_id: Yup.number().required("Please Select Department"),
    hire_date: Yup.date().required("Please Select Hire Date"),
    monthly_work_hours:  Yup.number().required("Monthly Work Hours is required"),
    pay_frequency: Yup.number().required("Pay Frequency is required"),
    report_to: Yup.string().when("position_id", {
        is: (value) => value !== 12,
        then: (schema) => schema.required("Report to is required"),
        otherwise: (schema) => schema.nullable().notRequired(),
      }),
});

关键修改点

  • otherwise分支改为schema.nullable().notRequired(),明确标记当position_id为12时,report_to字段为可选,消除Schema歧义;
  • then和otherwise使用函数接收Schema参数,确保链式调用的正确性,符合Yup官方推荐写法。

检查初始值

确保initialValues中的position_id初始值为数字类型(而非字符串),比如:

const initialValues = {
  // 其他字段...
  position_id: 0, // 或其他合法默认数字值
  report_to: ""
};

原理说明

当Yup的条件验证规则写法不严谨时,会触发隐性的Schema验证异常,Formik捕获到异常后会终止所有验证流程,表现为原有规则全部失效。修正后的写法明确了字段的可选性,同时遵循了Yup的链式调用规范,能恢复整个表单的验证逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:53:11