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-i…


This content originally appeared on DEV Community and was authored by qian

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


This content originally appeared on DEV Community and was authored by qian


Print Share Comment Cite Upload Translate Updates
APA

qian | Sciencx (2024-08-02T00:08:59+00:00) zod i18n internationalization. Retrieved from https://www.scien.cx/2024/08/02/zod-i18n-internationalization/

MLA
" » zod i18n internationalization." qian | Sciencx - Friday August 2, 2024, https://www.scien.cx/2024/08/02/zod-i18n-internationalization/
HARVARD
qian | Sciencx Friday August 2, 2024 » zod i18n internationalization., viewed ,<https://www.scien.cx/2024/08/02/zod-i18n-internationalization/>
VANCOUVER
qian | Sciencx - » zod i18n internationalization. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/02/zod-i18n-internationalization/
CHICAGO
" » zod i18n internationalization." qian | Sciencx - Accessed . https://www.scien.cx/2024/08/02/zod-i18n-internationalization/
IEEE
" » zod i18n internationalization." qian | Sciencx [Online]. Available: https://www.scien.cx/2024/08/02/zod-i18n-internationalization/. [Accessed: ]
rf:citation
» zod i18n internationalization | qian | Sciencx | https://www.scien.cx/2024/08/02/zod-i18n-internationalization/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.