DEV Community

qian
qian

Posted on

5

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up