• Stars
    star
    591
  • Rank 75,679 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Useful for translating zod error messages.

npm version codecov CI

hero

Zod Internationalization

This library is used to translate Zod's default error messages.

Installation

yarn add zod-i18n-map i18next

This library depends on i18next.

How to Use

import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";
// Import your language translation files
import translation from "zod-i18n-map/locales/es/zod.json";

// lng and resources key depend on your locale.
i18next.init({
  lng: "es",
  resources: {
    es: { zod: translation },
  },
});
z.setErrorMap(zodI18nMap);

const schema = z.string().email();
// Translated into Spanish (es)
schema.parse("foo"); // => correo invรกlido

makeZodI18nMap

Detailed customization is possible by using makeZodI18nMap and option values.

export type MakeZodI18nMap = (option?: ZodI18nMapOption) => ZodErrorMap;

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

Namespace (ns)

You can switch between translation files by specifying a namespace. This is useful in cases where the application handles validation messages for different purposes, e.g., validation messages for forms are for end users, while input value checks for API schemas are for developers.

The default namespace is zod.

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

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

๐Ÿ“ You can also specify multiple namespaces in an array.

Plurals

Messages using {{maximum}}, {{minimum}} or {{keys}} can be converted to the plural form.

Keys are i18next compliant. (https://www.i18next.com/translation-function/plurals)

{
  "exact_one": "String must contain exactly {{minimum}} character",
  "exact_other": "String must contain exactly {{minimum}} characters"
}
import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";

i18next.init({
  lng: "en",
  resources: {
    en: {
      zod: {
        errors: {
          too_big: {
            string: {
              exact_one: "String must contain exactly {{maximum}} character",
              exact_other: "String must contain exactly {{maximum}} characters",
            },
          },
        },
      },
    },
  },
});

z.setErrorMap(zodI18nMap);

z.string().length(1).safeParse("abc"); // => String must contain exactly 1 character

z.string().length(5).safeParse("abcdefgh"); // => String must contain exactly 5 characters

Custom errors

You can translate also custom errors, for example errors from refine.

Create a key for the custom error in a namespace and add i18n to the refine second arg(see example)

import i18next from "i18next";
import { z } from "zod";
import { makeZodI18nMap } from "zod-i18n-map";
import translation from "zod-i18n-map/locales/en/zod.json";

i18next.init({
  lng: "en",
  resources: {
    en: {
      zod: translation,
      custom: {
        my_error_key: "Something terrible",
        my_error_key_with_value: "Something terrible {{msg}}",
      },
    },
  },
});

z.setErrorMap(makeZodI18nMap({ ns: ["zod", "custom"] }));

z.string()
  .refine(() => false, { params: { i18n: "my_error_key" } })
  .safeParse(""); // => Something terrible

// Or

z.string()
  .refine(() => false, {
    params: {
      i18n: { key: "my_error_key_with_value", values: { msg: "happened" } },
    },
  })
  .safeParse(""); // => Something terrible happened

Handling object schema keys (handlePath)

When dealing with structured data, such as when using Zod as a validator for form input values, it is common to generate a schema with z.object. You can handle the object's key in the message by preparing messages with the key in the with_path context.

import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";

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

If _with_path is suffixed to the key of the message, that message will be adopted in the case of an object type schema. If there is no message key with _with_path, fall back to the normal error message.

Object schema keys can be handled in the message with {{path}}. By preparing the translated data for the same key as the key in the object schema, the translated value will be output in {{path}}, otherwise the key will be output as is. It is possible to access nested translation data by specifying handlePath.keyPrefix.

i18next.init({
  lng: "en",
  resources: {
    en: {
      zod: {
        errors: {
          invalid_type: "Expected {{expected}}, received {{received}}",
          invalid_type_with_path:
            "{{- path}} is expected {{expected}}, received {{received}}",
        },
      },
      form: {
        paths: {
          userName: "User's name",
        },
      },
    },
  },
});

z.setErrorMap(
  zodI18nMap({
    ns: ["zod", "form"],
    handlePath: {
      keyPrefix: "paths",
    },
  })
);

Translation Files

zod-i18n-map contains translation files for several locales.

It is also possible to create and edit translation files. You can use this English translation file as a basis for rewriting it in your language.

If you have created a translation file for a language not yet in the repository, please send us a pull request.

Use with next-i18next

Many users will want to use it with next-i18next (i.e. on Next.js). This example summarizes how to use with it.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

License

This project is licensed under the MIT License - see the LICENSE file for details

Contributors โœจ

All Contributors

Thanks goes to these wonderful people (emoji key):

Aiji Uejima
Aiji Uejima

๐Ÿ’ป ๐ŸŒ โš ๏ธ ๐Ÿค”
Ismail Ajizou
Ismail Ajizou

๐ŸŒ โš ๏ธ
Mohammed Maher
Mohammed Maher

๐ŸŒ โš ๏ธ
Luiz Oliveira Montedonio
Luiz Oliveira Montedonio

๐ŸŒ โš ๏ธ
Izayoi Hibiki
Izayoi Hibiki

๐ŸŒ โš ๏ธ
Hrafnkell Baldursson
Hrafnkell Baldursson

๐ŸŒ โš ๏ธ
Arturo
Arturo

๐ŸŒ โš ๏ธ
Nick Sulkers
Nick Sulkers

๐ŸŒ โš ๏ธ
Lukas
Lukas

๐ŸŒ โš ๏ธ
yodaka
yodaka

๐ŸŒ ๐Ÿ›
Tomer Yechiel
Tomer Yechiel

๐Ÿ’ป โš ๏ธ
Leonardo Montini
Leonardo Montini

๐ŸŒ โš ๏ธ
Recep ร‡iftรงi
Recep ร‡iftรงi

๐ŸŒ โš ๏ธ
TeraWattHour
TeraWattHour

๐ŸŒ โš ๏ธ
ๅ‡ฑๆฉKane
ๅ‡ฑๆฉKane

๐ŸŒ โš ๏ธ
fcrozatier
fcrozatier

๐ŸŒ ๐Ÿ›
Trond Albinussen
Trond Albinussen

๐ŸŒ โš ๏ธ
Christian Gil
Christian Gil

๐ŸŒ ๐Ÿ›
Artem Manchenkov
Artem Manchenkov

๐ŸŒ โš ๏ธ
Teodoro Villanueva
Teodoro Villanueva

๐Ÿ’ป
Willem Jan Weitering
Willem Jan Weitering

๐ŸŒ
Mendy Landa
Mendy Landa

๐ŸŒ โš ๏ธ
Px (Guilherme Ciota)
Px (Guilherme Ciota)

๐ŸŒ
Stรฉphane Raimbault
Stรฉphane Raimbault

๐ŸŒ
gabinbernard
gabinbernard

๐ŸŒ โš ๏ธ
Gabriel Majeri
Gabriel Majeri

๐ŸŒ โš ๏ธ
Karolis Kraujelis
Karolis Kraujelis

๐ŸŒ โš ๏ธ
Ihor
Ihor

๐ŸŒ โš ๏ธ

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

prisma-data-proxy-alt

This is a library to alternate and self-host the Prisma Data Proxy (cloud.prisma.io)
TypeScript
199
star
2

remix-esbuild-override

This is a library that makes it possible to change the configuration values of the Remix compiler (esbuild).
TypeScript
90
star
3

vitest-environment-vprisma

Vitest environment for testing with prisma.
TypeScript
70
star
4

next-with-split

This is a plugin for split testing (A/B testing) in Next.js.
TypeScript
68
star
5

next-qs-props

This library makes it possible to handle query strings in Next.js getStaticProps.
TypeScript
51
star
6

next-fortress

This is a Next.js plugin that redirects or rewrite for accesses that are not authenticated.
TypeScript
45
star
7

kiribi

๐ŸŽ‡ A simple job management library consisting of the Cloudflare stack.
TypeScript
43
star
8

turbo-with-prisma

TypeScript
26
star
9

next-image-loader

Plugin to transparently override the loader in next/image.
TypeScript
20
star
10

remix-service-bindings

TypeScript
17
star
11

use-postal-jp

้ƒตไพฟ็•ชๅทใ‚’ไฝๆ‰€ใซๅค‰ๆ›ใ™ใ‚‹Reactใ‚ซใ‚นใ‚ฟใƒ ใƒ•ใƒƒใ‚ฏใงใ™ใ€‚ไฝๆ‰€ใƒ‡ใƒผใ‚ฟใ‚’ๅ†…้ƒจใซๆŒใŸใšใ€APIใงไฝๆ‰€ๅค‰ๆ›ใ™ใ‚‹ใŸใ‚่ปฝ้‡ใชใƒ‘ใƒƒใ‚ฑใƒผใ‚ธใซใชใฃใฆใ„ใพใ™ใ€‚
TypeScript
17
star
12

prisma-fts-middleware

This library performs Prisma full-text search with external tools such as ElasticSearch, OpenSearch, and Algolia.
TypeScript
15
star
13

kv-cacheable

This library helps implement caching using Cloudflare Workers KV.
TypeScript
10
star
14

remix-emotion-on-cloudflare

TypeScript
9
star
15

sb-prisma

This is a project to make the supabase REST API available from PrismaClient.
TypeScript
9
star
16

blurhash-cf-worker

HTML
4
star
17

remix-chakra-ui-on-cloudflare

TypeScript
3
star
18

npm-runtime-search-api

TypeScript
3
star
19

authrize-preview-sample

TypeScript
3
star
20

vercel-og-on-cloudflare

TypeScript
3
star
21

remix-cf-service-bindings

JavaScript
2
star
22

cloudflare-meetup-nagoya-1

TypeScript
2
star
23

neon-sample

TypeScript
1
star
24

workers-cloud-gallery

TypeScript
1
star
25

cloudflare-fonts-example

TypeScript
1
star
26

botui-nx

TypeScript
1
star
27

saki-photo

TypeScript
1
star
28

cf-workers-event-tracker

TypeScript
1
star
29

botui

TypeScript
1
star
30

worker-puppetter

TypeScript
1
star
31

cfw-bq

This is a BigQuery client library for Cloudflare Workers. It allows you to query BigQuery from within a Cloudflare Worker.
TypeScript
1
star