skip to content

In Zod 4, how do you check that a sign-up form's password and confirmation match, and which field gets the error?

level: middleimportance: must knowfreq 65%

answer

  1. the object sees both fields
  2. the path option
  3. several issues need superRefine
  4. skipped after a type failure

basics

~20 s

In Zod 4, attach .refine() to the object schema, the only place both fields are visible, and pass path: ["confirmPassword"] so the issue lands on that field. Without path, the issue sits at the object's own path, which is empty at the root.

solid answer

~50 s

A field schema only sees its own value, so a rule that compares two fields goes on the **object**: `z.object({ password, confirmPassword }).refine((d) => d.password === d.confirmPassword, { error: "Passwords don't match", path: ["confirmPassword"] })`. The `path` option decides where the `"custom"` issue attaches; leave it out and the issue lands at the object's own path, which a form cannot show next to any input. When one rule can raise several issues, or issues with different paths or codes, use `.superRefine((data, ctx) => ...)` and call `ctx.addIssue({ code: "custom", message, path })` per problem, as in a booking date-range rule. Know when the check is skipped: an object-level refinement does not run if a field failed its type check, for example when a field is missing. A continuable issue such as a too-short password does not stop it, and the `when` option overrides the default.

go deeper

for a junior

Recall that cross-field rules live on the object schema and that the path option names the field that should show the message.

for a middle

Explain refine versus superRefine, how path is relative to the schema, and why a type failure in any field skips the object's refinements.

for a senior

Diagnose why a mismatch message vanished or landed at the root, and know when the when option is worth its complexity.

for a principal

Decide which business rules belong in shared schemas and which belong in the service layer, so client and server validate the same rules without duplicating database-backed checks.

## Why the rule goes on the object In Zod 4 every schema runs its own checks on its own value. `z.string().min(12)` on the `password` field cannot see `confirmPassword`, so a rule that compares two fields has to live one level up, on the object schema that holds both. A **cross-field rule** is therefore an object-level refinement: its function receives the whole parsed object. ```ts const SignUp = z .object({ email: z.email(), password: z.string().min(12), confirmPassword: z.string(), }) .refine((d) => d.password === d.confirmPassword, { error: "Passwords don't match", path: ["confirmPassword"], }); ``` ## Pointing the issue at a field with path Every issue carries a `path`, the list of keys from the root of the input to the value it describes. An object-level refinement runs at the object, so its issue would naturally get the object's path: an empty array at the root. A sign-up form that shows errors beside inputs has nothing to attach that to. - **`path: ["confirmPassword"]`** makes the issue describe the confirmation field, so form code reading issues by path shows the message beside it. - **Choosing the field is a product decision.** The confirmation is the usual target, because the user typed it second and is most likely to retype it. - **Paths are relative.** If `SignUp` is nested under an `account` key in a larger schema, the issue's path becomes `["account", "confirmPassword"]`, because a parent object prefixes its children's paths. ## superRefine when one rule raises several issues `.refine()` produces at most one issue per call, always with code `"custom"`. `.superRefine((value, ctx) => ...)` hands you a context with `ctx.addIssue()`, so one function can add any number of issues, each with its own `path`, message and code. ```ts const Booking = z .object({ startDate: z.iso.date(), endDate: z.iso.date() }) .superRefine((b, ctx) => { if (b.endDate <= b.startDate) { ctx.addIssue({ code: "custom", message: "End date must be after the start date", path: ["endDate"] }); } const nights = (Date.parse(b.endDate) - Date.parse(b.startDate)) / 86_400_000; if (nights > 30) { ctx.addIssue({ code: "custom", message: "Stays are limited to 30 nights", path: ["endDate"] }); } }); ``` ISO dates in `YYYY-MM-DD` form compare correctly as strings, which keeps the first test simple. Issues added this way are continuable by default. ## When the cross-field check does not run Object parsing happens in an order that decides whether your rule fires: 1. Each field is parsed by its own schema and runs its own checks. 2. Field issues are collected on the object, each with its `continue` flag. 3. The object's own refinements run, unless an earlier issue was **non-continuable**. A failed type check is non-continuable. If `confirmPassword` is missing, or any other field holds the wrong type, the match rule is skipped and the user sees only the type error. A failed `.min(12)` is continuable, so a too-short password still gets the mismatch message too. If you need the rule to run regardless of unrelated fields, the `when` option takes a function of the parse payload and returns whether the refinement should run; a common body re-parses just the two fields it compares. ## refine or superRefine | | `.refine()` | `.superRefine()` | |---|---|---| | Issues per call | One, when the function returns falsy | Any number, via `ctx.addIssue()` | | Issue code | Always `"custom"` | Any issue code you supply | | Where the issue lands | The `path` option, set once | A `path` on each issue | | Async | Accepts an async function | Accepts an async function | | Best for | One yes-or-no rule | Several related rules or conditional issues | ## Mistakes to avoid - Putting the comparison on a field schema, where the other field is not visible. - Leaving out `path` and then wondering why the form shows the error nowhere. - Expecting the match rule to report alongside a missing field's type error. - Reaching for `.superRefine()` for a single yes-or-no rule, where `.refine()` reads more clearly. - Throwing from the function instead of returning falsy or adding an issue. How those issues are then flattened into per-field messages is covered in the lesson on issue formatting.

  • In Zod 4, why does the password-match message not appear when an unrelated required field is missing?
    A missing field fails its type check with an `invalid_type` issue, and that issue is non-continuable. Object-level refinements are skipped once the payload holds a non-continuable issue, so the comparison never runs. A too-short password is different: length failures are continuable, so the match rule still runs. The `when` option lets you decide yourself whether the refinement should run.
  • When would you choose .superRefine() over two separate .refine() calls on the booking object?
    When the rules share work or depend on each other. One `.superRefine()` can parse the dates once, compare them, and add a separate issue for wrong order and for an over-long stay, each with its own path. Two `.refine()` calls work for independent rules, but each produces a single `"custom"` issue and repeats any shared computation.
  • If SignUp is nested under an account key in a bigger schema, what path does the mismatch issue get?
    `["account", "confirmPassword"]`. The `path` you set on a refinement is relative to the schema it is attached to, and each enclosing object prefixes its key as the issue travels up. You never write the full path yourself, so the same schema works at the root or nested.

  • Puts the password comparison on the confirmPassword field schema itself.
  • Says an object refinement without path attaches its issue to the last field it read.
  • Believes object refinements always run, even when a field failed its type check.
  • Claims only superRefine can read more than one field.
  • Thinks the path option must spell the full path from the root of the input.