In Zod 4, how does the error param set custom messages, and which Zod 3 options (message, errorMap, required_error, invalid_type_error) did it replace?
answer
- one param name for everything
- a string or a function
- undefined means defer
- no required issue code
- runs when parsing, not defining
basics
~20 sZod 4 takes one error param on schemas and checks: a string, or a function of the issue returning a message or undefined to defer. It replaces errorMap, deprecates message, and drops required_error and invalid_type_error.
solid answer
~50 sAlmost every Zod 4 schema factory and check accepts `error`: shorthand `z.string("Not text")`, the params form `{ error: "Not text" }`, or a function `(iss) => ...` that Zod calls at parse time with the raw issue, including its `code`, `input`, `path` and code-specific fields such as `minimum`. The function may return a string, `{ message }`, or `undefined` to hand control to the next error map. That function replaces Zod 3's `errorMap`, which Zod 4 no longer reads. The old `message` param still works but is deprecated, and passing both `message` and `error` throws. `required_error` and `invalid_type_error` are gone, because there is no `required` issue code: a missing key fails as `invalid_type` with `input` undefined. So you write `z.string({ error: (iss) => iss.input === undefined ? "Email is required" : "Email must be text" })`, and put rule-specific text on the check, as in `.min(8, "At least 8 characters")`.
code
typescript · 16 linesimport * as z from "zod";
const SignUp = z.object({
email: z.email({
error: (iss) => (iss.input === undefined ? "Email is required" : undefined),
}),
password: z
.string("Password must be text")
.min(8, { error: (iss) => `At least ${iss.minimum} characters` }),
});
const result = SignUp.safeParse({ password: "short" });
if (!result.success) {
console.log(result.error.issues.map((i) => i.message));
// [ 'Email is required', 'At least 8 characters' ]
}go deeper
Recall that Zod 4 uses one error param, as a string or a function, on both schemas and checks such as min.
Explain the function form: what the issue object carries, the three return types, and how iss.input === undefined replaces required_error.
Show migration judgment: find dead required_error and errorMap keys, know message is deprecated and cannot be combined with error, and place text on checks versus schemas deliberately.
Weigh hard-coded strings in shared schemas against code-driven wording, since schema text travels to every consumer and is awkward to translate later.
## One parameter for every customisation Each Zod **issue** has a `message`. By default the English locale writes it ("Invalid input: expected string, received number"). To write your own, Zod 4 has a single parameter, **`error`**, accepted by almost every schema factory and check. There are three ways to pass it: - **Shorthand string**: `z.string("Not text")`, `z.string().min(8, "At least 8 characters")`. - **Params object**: `z.string({ error: "Not text" })`, which you need when you also pass other params. - **Function**: `z.string({ error: (iss) => ... })`. In Zod's terminology a function like this is an **error map**. ## The error function Zod calls the function **at parse time**, when an issue arises, not when the schema is defined. It receives the raw issue, which carries: - `iss.code`, the issue code, such as `invalid_type` or `too_small`; - `iss.input`, the value that failed (present here even though the finalised issue drops it by default); - `iss.path`, the location of the failure; - `iss.inst`, the schema or check that raised the issue, and `iss.schema`, the schema that owns it; - code-specific fields, such as `iss.minimum` and `iss.inclusive` on a `too_small` issue. It can return: | Return value | Effect | |---|---| | a string | becomes the message | | `{ message: string }` | becomes the message | | `undefined` (or `null`) | defers to the next error map in the precedence chain | Returning `undefined` is the tool for selective customisation: handle the one code you care about and let Zod's defaults cover the rest. ## Required versus wrong type Zod has **no `required` issue code**. A key that is missing from the input reaches its field schema as `undefined` and fails with `invalid_type`. So the distinction lives in the error function: ```ts const Email = z.string({ error: (iss) => (iss.input === undefined ? "Email is required" : "Email must be text"), }); ``` A common mistake is reaching for `.min(1, "Required")`. That check only runs on a value that is already a string, so it catches the empty string but never a missing key. ## What Zod 4 replaced | Zod 3 | Zod 4 | |---|---| | `{ message: "..." }` | `{ error: "..." }`; `message` still accepted but deprecated | | `errorMap: (issue, ctx) => ({ message })` | `error: (iss) => string`, `{ message }` or `undefined` | | `ctx.defaultError` as the fallback | return `undefined` to defer | | `required_error`, `invalid_type_error` | an `error` function that inspects `iss.input` | Some details matter in a migration: 1. Passing **both** `message` and `error` throws an `Error` at schema construction ("Cannot specify both `message` and `error` params"). 2. `required_error` and `invalid_type_error` are not declared in Zod 4's params types, so TypeScript rejects them in an inline params object, and nothing in Zod reads them at runtime. Code that slipped past the compiler keeps validating but silently loses its custom wording. 3. `errorMap` is likewise gone from the params; its job is done by the function form of `error`, which no longer receives a `ctx` argument. 4. Error maps returning `{ message: ctx.defaultError }` become functions returning `undefined`. The changelog's reasoning: `required_error` and `invalid_type_error` could not be combined with `errorMap` and did not correspond to real issue codes. ## Interpolating parameters and handling several codes An error function can read the parameters of the rule that failed, so the wording never drifts from the schema: ```ts z.number().max(100, { error: (iss) => `At most ${iss.maximum}` }); ``` On a schema whose issues can have several codes, switch on `iss.code`: - return text for the codes you want to word yourself; - return `undefined` for every other code, so the locale's default still applies; - avoid a catch-all string, which would hide useful defaults such as the expected type. ## Where to put the text - **On the check** when the message is about that rule: `.min(8, "At least 8 characters")`. - **On the schema** when the message is about the field as a whole. Be aware that a schema-level message also covers issues raised by that schema's own checks when those checks define no message of their own. - **In a function** when the wording depends on the issue: missing versus wrong type, or a bound interpolated from `iss.minimum`. Because error functions run during parsing, a function that calls a translation helper picks up whatever language is current at that moment, and one schema definition can serve several languages.
- In Zod 4, why might a migrated schema still show the default English message for a missing field?If it still passes `required_error`, nothing in Zod 4 reads that key, so the missing field falls through to the locale's `invalid_type` message. TypeScript flags the key in an inline params object, but casts or untyped code hide it. Replace it with an `error` function that checks `iss.input === undefined`.
- When does a Zod 4 error function run, and why does that matter?It runs during `parse` or `safeParse`, when an issue arises, and its result is baked into that issue's `message`. So a function can read the current language or request state, and a schema defined once at module load still produces wording appropriate to each parse.
- required_error still sets the missing-field message in Zod 4.
- An error function must return an object with a message key.
- Returning undefined from an error function leaves the message empty.
- The error function runs once, when the schema is defined.
- Passing both message and error lets error win silently.
- .min(1, "Required") catches a missing key.
Assumes Zod 4; Zod 4 unified customisation under the error param, deprecated message, renamed errorMap to error, and dropped required_error and invalid_type_error.