Is there a way to name a field? #5287
-
Let say i have this schema
The error message for password is: "Too small: expected string to have >= 8 characters" is there a way to change "string" for the name of the field "password" without changing the whole error message so it becomes: "Too small: expected password to have >= 8 characters" The word string is not a word familiar to a user in my opinion. Also, if i use the french locale the traduction is: which does not make any sense since string is an english word |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @etiennelacoursiere! I'm Dosu and I’m helping the zod team. Zod doesn't automatically substitute type names (like To achieve your goal, you can customize error messages for each validation step using the export const LoginSchema = z.object({
email: z.email(),
password: z.string().min(8, { error: "Too small: expected password to have >= 8 characters" }).max(100),
}); If you want to keep the rest of the message dynamic, you can use an error function: password: z.string().min(8, {
error: (issue) => `Too small: expected password to have >= ${issue.minimum} characters`
}), For localization, you can set a global error map using import * as z from "zod";
z.config(z.locales.fr());
const original = z.locales.fr().localeError;
z.config({
localeError: (issue) => {
if (issue.code === "too_small" && issue.path[0] === "password") {
return `Trop petit : attendu que password ait >= ${issue.minimum} caractères`;
}
return original(issue);
}
}); If you have many fields, you'll need to repeat this pattern for each one, as Zod doesn't provide a built-in way to reference the field name in default error messages docs. Let me know if you need more help or if this answers your question—feel free to close the issue if you're all set! To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Hi @etiennelacoursiere! I'm Dosu and I’m helping the zod team.
Zod doesn't automatically substitute type names (like
string
) with field names (likepassword
) in its built-in error messages. This is because Zod's error messages are generated based on the type validation, not the field name, and schema metadata (such as a field "title") isn't reliably accessible in error maps due to how transformations work in Zod v4 discussion.To achieve your goal, you can customize error messages for each validation step using the
error
parameter. For example, you can set a custom error for themin
check on your password field: