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 };
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"
}
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" },
});
reference
- zod refine: https://zod.dev/?id=refine
- zod-i18n-map: https://github.com/aiji42/zod-i18n
Top comments (0)