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

如何用Yup验证Formik FieldArray中对象的唯一Email字段

实现Formik+Yup数组对象中Email字段的唯一性验证

修改后的验证规则代码

export const validationSchemaLifeSummarySecond = Yup.object().shape({
  employeeInfo: Yup.array().of(
    Yup.object().shape({
      name: Yup.string()
        .typeError("Preencha este campo")
        .required("Preencha este campo"),

      email: Yup.string()
        .required("Este campo é obrigatório")
        .email("Formato de e-mail incorreto")
        .typeError("Formato de e-mail incorreto")
        .test(
          "unique-email",
          "Este e-mail já está sendo utilizado",
          function(value) {
            // 跳过空值验证(required规则已处理空值)
            if (!value) return true;
            
            // 获取整个员工信息数组
            const employeeList = this.parent.parent.employeeInfo;
            // 解析当前字段所在的数组索引
            const currentIndex = parseInt(this.path.split('.')[1], 10);
            
            // 检查是否存在其他员工使用相同邮箱
            return !employeeList.some((emp, idx) => {
              return idx !== currentIndex && emp.email === value;
            });
          }
        ),
    })
  ),
});

逻辑说明

  • 上下文获取:通过this.parent.parent拿到表单根级数据,获取完整的employeeInfo数组;利用this.path(格式如employeeInfo.0.email)拆分出当前员工在数组中的索引。
  • 唯一性校验:用Array.some()遍历数组,排除当前元素后检查是否有重复邮箱。存在重复则返回false触发错误提示,否则返回true通过验证。
  • 空值兼容:添加空值判断,避免空邮箱触发唯一性校验(空值已由required规则处理)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:30:48