skip to content

Refinements and Transforms

Rules a shape cannot express, such as 'password matches confirmation', plus converting values with transform, preprocess, pipe and codecs. Interviewers ask where a cross-field error should attach.

on this pageshow

explore

questions

6

In Zod 4, what is the difference between adding .refine() and adding .transform() to a schema?

level: juniorimportance: must knowfreq 60%

answer

  1. check versus conversion
  2. what comes out of parse
  3. falsy return, custom issue
  4. a pipe into z.transform

basics

~20 s

In Zod 4, .refine() adds a custom check: its function returns truthy or falsy, the value passes through unchanged, and a falsy result records an issue with code custom. .transform() replaces the validated value with whatever its function returns.

solid answer

~50 s

`.refine(fn, { error })` is a **check**: Zod calls `fn` with a value that already has the schema's type, and a falsy return adds one issue with code `"custom"` while the value itself is left alone. `.transform(fn)` is a **conversion**: in Zod 4 it is shorthand for piping the schema into `z.transform(fn)`, so it runs only when nothing before it raised an issue, and parsing returns the function's result, such as a trimmed price string turned into a `number`. Neither function should throw, because Zod does not catch thrown errors: a refinement signals failure by returning falsy, and a transform reports a problem by pushing an issue onto `ctx.issues` and returning `z.NEVER`. The working rule is simple: if the value should come out the same, refine it; if it should come out different, transform it.

code

typescript · 7 lines
typescript
import * as z from "zod";

const HasAt = z.string().refine((s) => s.includes("@"), { error: "Missing @" });
HasAt.parse("[email protected]"); // "[email protected]" (unchanged)

const Length = z.string().transform((s) => s.length);
Length.parse("[email protected]"); // 15 (converted)

go deeper

for a junior

Remember the split: refine says yes or no and keeps the value, transform returns a new value. Be ready to say what parse returns in each case.

for a middle

Explain that a refinement's issue is continuable by default, that abort stops later checks, and that a transform is a pipe which never runs after an earlier issue.

for a senior

Show you know why neither function may throw, how ctx.issues with z.NEVER reports a failed conversion, and how chain order decides which value a refinement inspects.

for a principal

Talk about keeping schemas declarative: built-in checks stay visible to anything that reads the schema, while transforms make input and output differ, which shapes how a team shares one schema across layers.

## Two different jobs Zod 4 schemas do two kinds of work after the basic type check. A **refinement** asks a yes-or-no question about a value the schema has already accepted ("is this string at most 255 characters?", "does the confirmation equal the password?"). A **transform** turns the accepted value into something else ("trim this", "turn the text `"19.99"` into the number `19.99`"). `.refine()` and `.transform()` are the everyday methods for each job, and mixing them up is the most common way a schema ends up returning the wrong thing. ## How .refine() behaves `.refine(fn, params)` appends a custom check to the schema's list of checks. - **Return value is a verdict.** Zod treats a truthy return as a pass and a falsy one as a failure. The return value never becomes the parsed value: `z.string().refine((s) => s.includes("@")).parse("[email protected]")` returns the string, not `true`. - **Failure produces one issue** with code `"custom"`. The `error` option sets its message, either as a string or as a function of the issue. - **Other checks keep running.** By default a refinement's issue is *continuable*, so later checks still execute and Zod reports as many problems as it can at once. `abort: true` makes a failing refinement stop the checks after it. - **It is skipped after a type failure.** If the value never got past the type check (a number where a string was expected), refinements do not run, so your function never receives a value of the wrong type. - **`path` re-targets the issue**, which matters on object schemas for cross-field rules. ## How .transform() behaves `.transform(fn)` is sugar for `schema.pipe(z.transform(fn))`, and the method returns a pipe. - **It runs only on clean input.** A pipe stops as soon as the schema on its left reports an issue, so a transform never sees a value that failed validation. The single exception is an unknown-key issue from a strict object, which describes extra keys rather than the value. - **Its return value is the new value.** Whatever the function returns is what `parse` hands back, and any refinement chained *after* the transform sees the converted value. - **Problems are reported through `ctx`.** The second argument lets you push an issue onto `ctx.issues`; returning `z.NEVER` then exits without affecting the result's type. - **Async functions need the async parse methods** (`parseAsync`, `safeParseAsync`); a synchronous parse throws when it meets one. ## Order matters when you chain them Checks and transforms run in the order you write them. Consider a price field: ```ts const Price = z .string() .trim() .min(1, { error: "Price is required" }) .transform((s) => Number(s)) .refine((n) => Number.isFinite(n) && n > 0, { error: "Price must be a positive number" }); Price.parse(" 19.99 "); // 19.99 Price.parse("abc"); // ZodError: Price must be a positive number ``` 1. `.trim()` and `.min(1)` run on the string. 2. If neither raised an issue, the transform converts the string to a number. 3. The final `.refine()` runs on the number, because it is attached after the transform. Move the refinement before the transform and its function would receive the string instead. ## Side by side | | `.refine()` | `.transform()` | |---|---|---| | Purpose | Accept or reject | Convert | | What `parse` returns | The same value | The function's return value | | How it fails | Falsy return, one `"custom"` issue | Push onto `ctx.issues`, return `z.NEVER` | | Runs when earlier checks failed | Yes, after continuable issues; no after a type failure | No, any earlier issue stops the pipe | | Built on | A custom check in the schema | A pipe into `z.transform()` | ## Mistakes to avoid - Returning a converted value from `.refine()` and expecting `parse` to return it. - Returning `false` from a transform to signal failure: `false` simply becomes the output. - Throwing inside either function. Zod does not catch thrown errors, so the exception escapes `parse` and even `safeParse`. - Writing a custom function for a rule that a built-in such as `.min()`, `.max()` or `.regex()` already expresses. Built-in checks are visible on the schema, for example as a string schema's `minLength` property, while a custom function is opaque. How a transform changes the static input and output types is covered in the lesson on schema-derived types; this lesson keeps the runtime behaviour.

  • In Zod 4, how do you report a failed conversion from inside a .transform()?
    Use the second argument. Push an issue such as `{ code: "custom", message: "Not a number", input: val }` onto `ctx.issues`, then return `z.NEVER`. That records a normal issue, so `safeParse` returns a failure, and `z.NEVER` lets the function exit without widening its return type. Throwing does not work, because Zod does not catch thrown errors.
  • If a refinement is chained after a transform, which value does it see?
    The transformed one. `.transform()` returns a pipe, and a `.refine()` called on that pipe attaches a check that runs on the pipe's output. So `z.string().transform(Number).refine((n) => n > 0)` receives a number. Put the refinement before the transform if it needs the original string.

  • Says the value a refine function returns becomes the parsed value.
  • Returns false from a transform to make parsing fail.
  • Throws inside a refinement and expects Zod to turn it into an issue.
  • Believes a transform still runs when the schema before it reported an issue.
  • Thinks the first failed refinement always stops every later check.
open as a page

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%

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.

open as a page

In Zod 4, what is the difference between .default(), .prefault() and .catch() on a schema?

level: middleimportance: should knowfreq 35%

basics

~20 s

In Zod 4, .default() returns its value as-is when the input is undefined, skipping validation. .prefault() substitutes its value for undefined and then parses it. .catch() returns its fallback whenever validation fails, whatever the input was.

open as a page

In Zod 4, you add an async .refine() that checks whether a sign-up username is already taken, and every caller already uses safeParseAsync. What can still go wrong?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In Zod 4, the lookup still runs after continuable failures such as a too-short name, unless that check sets abort true or the refinement uses when. A rejected lookup escapes as an exception, not an issue, and the check is only a pre-check; the store's uniqueness rule is the real guarantee.

open as a page

In Zod 4, when normalising an email and a price string on input, how do .transform(), z.preprocess() and .pipe() differ in when they run?

level: seniorimportance: should knowfreq 45%

basics

~20 s

In Zod 4, z.preprocess() runs a function on the raw, unknown input before its target schema validates it. .transform() runs only after its schema has accepted the value. .pipe() feeds one schema's output into a second schema, which validates the converted value.

open as a page

In Zod 4, what does a z.codec() give you over .transform() when a booking timestamp crosses the network as an ISO string?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Since Zod 4.1, z.codec(in, out, { decode, encode }) defines a two-way conversion: parse or decode turns the ISO string into a Date, and encode turns the Date back into a validated string. A .transform() only runs forward, and encoding through one throws.

open as a page