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

react-i18next结合Zod与后端,校验消息翻译失效问题求助

解决Zod校验错误消息无法通过react-i18next翻译为荷兰语的问题

核心问题定位

你的问题本质是zod-i18n-map的翻译资源未被正确加载到i18next实例中,或者Zod未绑定到已配置的i18next翻译函数,导致默认英文错误消息未被替换。

关键修复步骤

1. 修正链式后端配置顺序

检查i18n.js,确保i18next-chained-backend先加载zod本地资源,再加载你的API翻译资源——顺序错误会导致zod资源被覆盖:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import ChainedBackend from 'i18next-chained-backend';
import HttpBackend from 'i18next-http-backend';
import resourcesToBackend from 'i18next-resources-to-backend';
import { zodI18nMap } from 'zod-i18n-map';
import nlZod from 'zod-i18n-map/locales/nl/zod.json';

i18n
  .use(ChainedBackend)
  .use(initReactI18next)
  .init({
    lng: 'nl',
    fallbackLng: 'en',
    interpolation: { escapeValue: false },
    debug: false, // 可开启调试查看资源加载日志
    backend: {
      backends: [
        // 优先加载zod的荷兰语翻译资源
        resourcesToBackend((lng, ns) => {
          if (ns === 'zod' && lng === 'nl') return Promise.resolve(nlZod);
          return Promise.resolve({});
        }),
        // 再加载API提供的业务翻译资源
        HttpBackend
      ],
      backendOptions: [
        {}, // 对应zod资源的空配置
        { loadPath: '/api/translations/{{lng}}/{{ns}}' } // 你的HTTP后端配置
      ]
    }
  });

export default i18n;

2. 绑定Zod到i18next翻译函数

必须替换Zod默认的错误消息生成逻辑,让它使用i18next的t函数。这段代码要放在所有Zod Schema定义之前执行:

import { z } from 'zod';
import i18n from './i18n';

// 配置Zod使用i18next的翻译能力
z.setErrorMap((issue, ctx) => {
  const message = i18n.t(`zod:${issue.code}`, {
    ...ctx,
    ...issue.params,
  });
  return { message };
});

3. 验证zod命名空间调用

手动调用t函数时必须指定zod命名空间,否则会找不到对应资源:

// 错误写法:t('required')
// 正确写法:指定命名空间
console.log(i18n.t('required', { ns: 'zod' }));

如果仍返回原始字符串,开启i18n的debug: true模式,查看控制台是否有zod命名空间的加载报错。

4. 确认zod荷兰语资源完整性

检查node_modules/zod-i18n-map/locales/nl/zod.json,确认包含你需要的错误码(比如required、invalid_type等),确保资源文件本身没有缺失。

测试验证

定义简单Schema测试翻译效果:

const UserSchema = z.object({
  username: z.string()
});

// 测试空值输入,应返回荷兰语"Verplicht"
console.log(UserSchema.safeParse({}).error?.issues[0].message);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:07:13