DEV Community

qian
qian

Posted on

zod i18n internationalization

background

using zod for validation, and need to internationalize the application.

requirements

zod zod-i18n-map

create a zod instance with i18n

i18.ts

import { z } from "zod";
import { makeZodI18nMap } from "zod-i18n-map";

// these two namespaces need to add to the i18n init config's ns.
z.setErrorMap(makeZodI18nMap({ ns: ["zod", "custom"] }));
export { z };
Enter fullscreen mode Exit fullscreen mode

customize errors in zod i18n

the 'custom' namespace is for custom error messages.
custom.json

{
  "password": "at least six characters required",
  "confirm": "passwords don't match"
}
Enter fullscreen mode Exit fullscreen mode

how to configure custom error messages in zod schema

using refine method, the first params is to check if the input is valid.
passing the i18n key to params.i18n

const formSchema = z.object({
  password: z
    .string()
    .refine((value) => /^[a-zA-Z0-9#?!@$%^&*-]{6,255}/.test(value), {
      params: { i18n: "password" },
    }),
});

// below won't work because when run regex() it throws error already.
z.string()
  .regex(/^[a-zA-Z0-9#?!@$%^&*-]{6,255}/)
  .refine(false, {
    params: { i18n: "password" },
  });
Enter fullscreen mode Exit fullscreen mode

reference

Top comments (0)