Skip to content

zod-i18n-map-v2.0.0

Compare
Choose a tag to compare
@github-actions github-actions released this 20 Dec 14:14
· 278 commits to main since this release
e6a3410

zod-i18n-map-v2.0.0 (2022-12-20)

Features

i18next.init({
  lng: 'en',
  resources: {
    en: { 
      zod: { // default namespace
        invalid_type: "Error: expected {{expected}}, received {{received}}"
      },
      formValidation: { // custom namespace
        invalid_type: "it is expected to provide {{expected}} but you provided {{received}}"
      },
    },
  },
});

// use default namespace
z.setErrorMap(makeZodI18nMap())
z.string().parse(1) // => Error: expected string, received number

// select custom namespace
z.setErrorMap(makeZodI18nMap({ ns: 'formValidation' }))
z.string().parse(1) // => it is expected to provide string but you provided number
  • handling object schema keys in error messages (f75f458): See here
i18next.init({
  lng: "en",
  resources: {
    en: {
      zod: {
        errors: {
          invalid_type: "Expected {{expected}}, received {{received}}",
          invalid_type_with_path:
            "{{path}} is expected {{expected}}, received {{received}}",
        },
        userName: "User's name",
      },
    },
  },
});

z.setErrorMap(zodI18nMap);

z.string().parse(1) // => Expected string, received number

const schema = z.object({
  userName: z.string(),
});
schema.parse({ userName: 1 }) // => User's name is expected string, received number

BREAKING CHANGES

  • the argument type of makeZodI18nMap changes
export type MakeZodI18nMap = (option?: ZodI18nMapOption) => ZodErrorMap;

export type ZodI18nMapOption = {
  t?: i18n["t"];
  ns?: string | readonly string[]; // See: `Namespace`
  handlePath?: { // See: `Handling object schema keys`
    context?: string;
    ns?: string | readonly string[];
    keyPrefix?: string;
  }; 
};