What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation?

If I want to use i18n for error messages in Yup, I would do the following:

import { t } from "i18next";
import * as yup from "yup";
import "./i18next";

yup.setLocale({
  mixed: {
    required: () => t("validation:required"),
  },
  string: {
    min: ({ min }) => t("validation:minStr", { value: min }),
    max: ({ max }) => t("validation:maxStr", { value: max }),
  },
  array: {
    min: ({ min }) => t("validation:minArr", { value: min }),
    max: ({ max }) => t("validation:maxArr", { value: max }),
  },
});
export default yup;

Is it possible to achieve the same in Zod?

Answer №1

To customize error messages using Zod, you can utilize the z.setErrorMap(errorMap) method as shown in the documentation:

import { z } from "zod";

const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
  if (issue.code === z.ZodIssueCode.invalid_type) {
    if (issue.expected === "string") {
      return { message: "bad type!" };
    }
  }
  if (issue.code === z.ZodIssueCode.custom) {
    return { message: `less-than-${(issue.params || {}).minimum}` };
  }
  return { message: ctx.defaultError };
};

z.setErrorMap(customErrorMap);

For internationalization support, the recommended library is zod-i18n (also known as zod-i18n-map on npm). It requires a peer dependency on i18next. Here is an example usage from their README:

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";

// Adjust lng and resources keys based 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The material-table is utilizing a component as data, but is failing to pass the component context during the onChange

I attempted to include a component as data in a material table, but I'm facing an issue with accessing the 'this' context of the component to update the state within the onChange function. Unfortunately, the editable feature offered by mater ...

Best practices for efficiently updating state in React components

Currently, I am in the process of learning React and trying to grasp its concepts by practicing. One exercise I decided to tackle involves deleting an element from an array when a user clicks on it in the UI. Below is the code snippet that I have been work ...

Tips on maintaining the parent's scope in CoffeeScript while making an AJAX call

I need to iterate through an object in CoffeeScript and make an AJAX call for each item in the object using jQuery. However, I'm facing an issue with losing the reference to the initial context in the callback function of the AJAX call. The context al ...

What is the best way to implement pipes and incorporate reusable action buttons in a Mat-table component for maximum reusability?

I am seeking assistance in creating a reusable component for the Angular Material Mat-table. I have made progress on loading data from the parent component to the child component, as can be seen in StackBlitz, but I now want to apply pipes to the data bef ...

What is the best method for passing page props in Next.JS?

One example is using the React Context API to pass props from the _app file to pages. Another scenario involves refactoring a ReactJS routing, where state is passed from app.js to pages through the route definition as shown below: <Route><Compon ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

Tips for adjusting image hues in Internet Explorer?

I have successfully altered the colors of PNG images in Chrome and Firefox using CSS3. Here is my code: #second_image{ -webkit-filter: hue-rotate(59deg); filter: hue-rotate(59deg); } <img src='http://i.im ...

Unable to utilize the web-assembly Rust implementation due to the error stating 'Cannot access '__wbindgen_throw' before initialization'

Looking to integrate some web-assembly into my project, I started off by testing if my webpack setup was functioning properly and able to utilize my .wasm modules. Here's a snippet of what I came up with: #[wasm_bindgen] pub fn return_char() -> cha ...

Adjusting the quantity of buttons in real-time following an ajax request

Creating buttons dynamically in an Ajax success function can be a challenge when the number of buttons varies each time. I am able to create the buttons, but since the exact number is unknown, adding the correct number of button listeners becomes tricky. ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

Tips for resolving the Range issue with jQuery-UI slider and activating a function when changes are made

I created a simple form that calculates an estimated price based on quantity and one of three options. Then, I attempted to integrate a jQuery-UI slider into the form. However, I encountered an issue where the slider was displaying values outside of the sp ...

Sending data to a MySQL database using AJAX with PHP

While attempting to use ajax to insert a value in PHP, I am encountering an issue where the data is not getting inserted into the database. The code snippet I am using was sourced from answers provided on this site. Can someone please point out where I m ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

How can I implement a page switch in vuejs by clicking on a name in a table list?

I'm currently working on a list page in VueJS and facing some challenges. Here is the code snippet: <template> <vue-good-table :columns="columns" :rows="row" :search-options="{ ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

"Enhanced visuals with parallax scrolling feature implemented on various sections for an engaging

With 4 sections, each featuring a background image and text in the middle, I encountered an issue when attempting to have them fixed while scrolling. The goal was for the section below the first one to overlap the one above it along with its text as we scr ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

Can anyone provide guidance on setting up a TypeScript service worker in Vue 3 using the vite-plugin-pwa extension?

I am looking to develop a single-page application that can be accessed offline. To achieve this, I have decided to implement a PWA Service Worker in my Vue webapp using TypeScript and Workbox. I found useful examples and guidance on how to do this at . Ho ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...