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?
answer
- before or after validation
- unknown goes into preprocess
- any issue stops a pipe
- checks run in written order
basics
~20 sIn 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.
solid answer
~40 sAll three are pipes in Zod 4: `.transform(fn)` is `schema.pipe(z.transform(fn))` and `z.preprocess(fn, schema)` is `z.transform(fn).pipe(schema)`. A pipe runs its left side, stops if that raised an issue, and otherwise passes the value right. For an email, `z.string().trim().toLowerCase().pipe(z.email())` cleans the string with overwrite checks and then validates the format; `z.email().trim()` checks the format first, so padded input fails. For a price, validate the text with `.regex()`, convert with `.transform(Number)`, then `.pipe(z.number().positive())` so a bad conversion is still caught, since `z.number()` rejects `NaN`. Reach for `z.preprocess()` only when the raw input may not even be a string; its function receives `unknown`, so it must guard every type.
code
typescript · 14 linesimport * as z from "zod";
const Email = z.string().trim().toLowerCase().pipe(z.email());
Email.parse(" [email protected] "); // "[email protected]"
const Price = z
.string()
.trim()
.regex(/^\d+(\.\d{1,2})?$/, { error: "Use a plain amount such as 19.99" })
.transform(Number)
.pipe(z.number().positive().max(100_000));
Price.parse(" 19.99 "); // 19.99
Price.safeParse("1e3").success; // false: rejected by the regex before conversiongo deeper
Recall the order: preprocess runs before validation, transform after, and pipe hands one schema's result to another schema.
Explain that transform and preprocess are both pipes, that any left-side issue stops a pipe, and that overwrite checks run in written order.
Show how you would normalise and convert input so every step is validated, and spot the z.email().trim() ordering trap in review.
Weigh permissive preprocess functions against narrow, explicit pipelines when setting team conventions for what input formats an API accepts.
## Three tools, three moments Zod 4 gives you three ways to change a value on its way in, and the difference between them is **when** they run relative to validation. | Tool | Runs on | Input it receives | Sees invalid input? | |---|---|---|---| | `z.preprocess(fn, schema)` | Before `schema` | The raw value, typed `unknown` by default | Yes, it runs first | | `schema.transform(fn)` | After `schema` | The value `schema` accepted | No | | `a.pipe(b)` | After `a` | `a`'s output, which `b` validates | No | | `.trim()`, `.toLowerCase()` | In the check list | The current string | After continuable issues yes; after a type failure no | Under the hood `.transform(fn)` is `schema.pipe(z.transform(fn))`, and `z.preprocess(fn, schema)` is `z.transform(fn).pipe(schema)`. Both return a pipe, so one rule explains all of them: **a pipe runs its left side, stops if that produced any issue, and otherwise hands the value to its right side.** ## The email: normalise, then validate A sign-up email should be trimmed and lower-cased before its format is checked, so `" [email protected] "` is stored as `"[email protected]"`. ```ts const Email = z.string().trim().toLowerCase().pipe(z.email()); ``` - `.trim()` and `.toLowerCase()` are **overwrite checks**: they replace the string with a new string of the same type, in the order you wrote them. - `.pipe(z.email())` then checks the format on the cleaned value. - `z.email().trim()` looks equivalent but is not. On a format schema the format check comes first in the check list, so it inspects the untrimmed value and padded input fails, even though the trim runs afterwards. ## The price string: validate the text, convert, validate the number A price arrives as text, perhaps with stray spaces, and must leave as a positive number. ```ts const Price = z .string() .trim() .regex(/^\d+(\.\d{1,2})?$/, { error: "Use a plain amount such as 19.99" }) .transform(Number) .pipe(z.number().positive().max(100_000)); ``` 1. `z.string()` rejects anything that is not text. 2. `.trim()` cleans it, and `.regex()` checks the cleaned text has a plain decimal shape, so `"1e3"` and `"12px"` fail with a clear message. 3. `.transform(Number)` runs only if no issue was raised so far. 4. `.pipe(z.number()...)` validates the converted number. `z.number()` rejects `NaN` and infinite values, so a conversion that went wrong is still caught. Checking the text **before** converting it is what keeps the error message meaningful: `Number("12px")` is `NaN`, and `z.number()` would report a type error the user cannot act on. ## When z.preprocess() is the right tool `z.preprocess()` is for input whose type you cannot rely on, where the target schema would otherwise reject the value before any `.transform()` could run. - A field that may arrive as a number or as a string, where you want one rule for both. - Turning an empty string into `undefined` so a following optional schema treats it as absent. - Normalising legacy payloads with shapes that vary. Because the function receives `unknown`, it must guard every branch: ```ts const PriceFromAnything = z.preprocess( (v) => (typeof v === "string" ? Number(v.trim()) : v), z.number().positive() ); ``` That flexibility is also its cost. `Number(" 1e3 ")` is `1000`, so this version accepts a format the regex version refuses. A narrower `z.string()` plus checks plus a pipe keeps each step explicit. ## How a pipe stops - Any issue on the left side stops the pipe, whether continuable or not. The one exception is an `unrecognized_keys` issue, which describes extra input keys rather than the value being piped. - A transform therefore never receives a value that failed validation, so it can assume the shape it was given. - Transform and preprocess functions should never throw; report a problem through `ctx.issues` and return `z.NEVER`. - An async function anywhere in the chain means you must parse with `parseAsync` or `safeParseAsync`. ## Mistakes to avoid - Converting with `.transform()` and never validating the result, so `NaN` flows into the application. - Writing `z.email().trim()` and expecting padded addresses to pass. - Using `z.preprocess()` with no type guard and calling string methods on a value that is not a string. - Relying on a preprocess conversion that accepts far more formats than the product means to allow. How a transform or preprocess changes the static input type is covered in the lesson on schema-derived types; this lesson keeps the runtime order.
- Why validate the price text with a regex before converting it, when z.number() rejects NaN anyway?For the message and for the formats you accept. `Number("12px")` is `NaN`, so `z.number()` reports a type error the user cannot act on, and `Number("1e3")` is a valid `1000` that `z.number()` happily accepts. A regex on the trimmed text rejects both with a message such as "Use a plain amount", and the pipe into `z.number()` stays as a final guard.
- In Zod 4, does a transform run if the string schema before it raised only a continuable issue, such as a failed min length?No. A pipe stops on any issue from its left side, continuable or not, except an `unrecognized_keys` issue. Continuable only means later checks on the same schema keep running so more problems are reported; it never lets a transform receive a value that failed validation.
- Says z.preprocess() runs after its target schema has validated the value.
- Believes z.email().trim() trims before the email format is checked.
- Converts with .transform(Number) and never validates the resulting number.
- Thinks a transform still runs after a continuable issue on the schema before it.
- Calls string methods inside z.preprocess() without checking the input type first.