使用 next-intl 翻译 zod 错误消息的解决方案

问题描述 投票:0回答:1

我正在寻找一种在使用 next-intl 包时翻译 Zod 错误消息的方法。也许是Zod-i18n的替代品,而不是i18next

选择 next-intl 而不是 i18next 的原因主要与 Next13 应用程序路由器的实验有关,因此在这种情况下切换到 i18next 确实不是一个选择。

next.js internationalization next.js13 i18next zod
1个回答
0
投票

您可以将翻译作为参数传递。

en.json:

{
  "home": {
    "errors": {
      "Name is required": "Name is required."
    }
  }
}

模式/index.ts:

import * as z from "zod";

export const BaseSchema = (t: (arg: string) => string) =>
  z.object({
    name: z.string().min(1, {message: t("errors.Name is required")})
  });

在客户端代码(表单)中:

"use client";

import { useTranslations } from "next-intl";
import { BaseSchema } from "@/schemas";


const t = useTranslations("home");
const formSchema = BaseSchema(t);
const form = useForm<z.infer<typeof formSchema>>({
  resolver: zodResolver(formSchema),
  defaultValues: {
    name: ""
});

const onSubmit = async (values: z.infer<typeof formSchema>) => {
  // await a server action 
};

在服务器操作代码中:

"use server";

import { getTranslations } from "next-intl/server";
import * as z from "zod";
import { BaseSchema } from "@/schemas";

export const create = async (
  values: z.infer<ReturnType<typeof BaseSchema>>
) => {
  const t = await getTranslations("home");
  const paramsSchema = BaseSchema(t);
  const validatedFields = paramsSchema.safeParse(values);
  if (!validatedFields.success) {
    throw new Error("Invalid fields");
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.