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

使用Zod验证邮箱:多字段错误提示失效问题求助

Zod实现邮箱与确认邮箱不匹配时双字段报错提示

Zod的refine方法path属性仅支持指定单个字段路径,直接传数组['email', 'confirmEmail']不符合API规范,所以会出现未定义错误。要让两个字段同时显示匹配错误,可采用以下两种方案:

方案一:使用superRefine手动添加多字段错误

superRefine支持在一次校验逻辑中,为多个字段自定义添加错误信息,完美适配需求:

const SignUpFormInputsSchema = z.object({
  email: z
    .string({
      required_error: '邮箱不能为空。',
      invalid_type_error: '邮箱格式无效。',
    })
    .email('邮箱格式无效。'),
  confirmEmail: z
    .string({
      required_error: '确认邮箱不能为空。',
      invalid_type_error: '确认邮箱格式无效。',
    })
    .email('确认邮箱格式无效。'),
}).superRefine(({ email, confirmEmail }, ctx) => {
  if (email !== confirmEmail) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: '两次输入的邮箱不匹配。',
      path: ['email'],
    });
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: '两次输入的邮箱不匹配。',
      path: ['confirmEmail'],
    });
  }
});

方案二:为两个字段分别添加依赖校验

给email和confirmEmail各自添加refine校验,通过ctx.parent获取对方字段的值,判断是否匹配:

const SignUpFormInputsSchema = z.object({
  email: z
    .string({
      required_error: '邮箱不能为空。',
      invalid_type_error: '邮箱格式无效。',
    })
    .email('邮箱格式无效。')
    .refine((value, ctx) => {
      const confirmEmail = ctx.parent.confirmEmail;
      // 仅当确认邮箱已填写时才校验匹配
      if (confirmEmail && value !== confirmEmail) {
        return false;
      }
      return true;
    }, '两次输入的邮箱不匹配。'),
  confirmEmail: z
    .string({
      required_error: '确认邮箱不能为空。',
      invalid_type_error: '确认邮箱格式无效。',
    })
    .email('确认邮箱格式无效。')
    .refine((value, ctx) => {
      const email = ctx.parent.email;
      if (email && value !== email) {
        return false;
      }
      return true;
    }, '两次输入的邮箱不匹配。'),
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:23:14