全局配置zod校验信息

669 阅读1分钟

简介

使用zod做校验的时候,默认校验信息是英文。如果需要自定义为中文信息,有下面几种方法。

小结

几个方法使用下来,比较推荐的是zod-i18n+zod-validation-error组合,如果需要自定义校验类型,可以使用custom-schemas

// zod-i18n + zod-validation-error 组合后的效果
{ "code": -1, "message": "Validation error: 预期输入为字符串,而输入为数字 at \"rolename\"; 预期输入为字符串,而输入为数字 at \"rolekey\"; 错误的枚举值 'NORMA12L'。请输入 'NORMAL' | 'DISABLE' at \"status\"" }

1. 每个字段自定义

const roleSchema = z
  .object({
    name: z.string({
      invalid_type_error:"类型错误",
      required_error:"必须填写",
      message: "自定义消息"
    }).optional().default("测试"),
    ...
  })

2. 全局自定义Error Map

官方文档藏在ERROR_HANDLING.md这里,有点难找,mark一下。

import { z } from "zod";

export const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
  if (issue.code === z.ZodIssueCode.invalid_type) {
    if (issue.expected === "string") {
      return { message: "必须为字符串!" };
    }
  }
  if (issue.code === z.ZodIssueCode.custom) {
    return { message: `less-than-${(issue.params || {}).minimum}` };
  }
  return { message: ctx.defaultError };
};

z.setErrorMap(customErrorMap)

3. 使用zod-i18n国际化翻译中文信息

仓库地址:github.com/aiji42/zod-…

import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";
import translation from "zod-i18n-map/locales/zh-CN/zod.json";

// 设置国际化
i18next.init({
  lng: "zh-CN",
  resources: {
    "zh-CN": { zod: translation },
  },
});
z.setErrorMap(zodI18nMap);

// 暴露zod实例
export { z };

错误信息友好化

zod-validation-error 可以把zod的错误信息格式化为相对友好的信息展示。

// zod错误信息
[
  {
    "code": "too_small",
    "inclusive": false,
    "message": "Number must be greater than 0",
    "minimum": 0,
    "path": ["id"],
    "type": "number"
  },
  {
    "code": "invalid_string",
    "message": "Invalid email",
    "path": ["email"],
    "validation": "email"
  }
]

// zod-validation-error 格式化后的 错误信息
Validation error: Number must be greater than 0 at "id"; Invalid email at "email"