Sub topic 11
Custom rules with refine
Built-in checks such as min, max, email, and regex cover the common cases. Some rules do not fit them: two fields must match, a date range must be ordered, or a value must pass a lookup. refine lets you attach your own rule to any schema.
This chapter assumes you know z.object, safeParse, and how to read error.issues. The examples work with Zod 3 and Zod 4.
What refine does
refine takes a function that receives the parsed value and returns true when the value is acceptable. A falsy return value creates a validation issue. Zod runs your function only after the base schema has accepted the value. Inside the function you can rely on the base type.
import { z } from "zod";
const Slug = z
.string()
.min(1)
.refine((value) => /^[a-z0-9-]+$/.test(value), {
message: "Use lowercase letters, digits, and hyphens only",
});
console.log(Slug.safeParse("my-post-1").success); // true
console.log(Slug.safeParse("My Post").success); // falseThe second argument can be a plain string, which is shorthand for the message. It can also be an object with message and path. If you pass nothing, the issue message is the generic Invalid input. A good message is part of the rule, so always write one.
The issue created by refine has the code custom. You can use that code to tell your own rules apart from built-in failures when you format errors.
Cross-field rules on objects
A rule on one field cannot see the other fields. To compare fields, call refine on the object schema. The callback receives the whole parsed object.
import { z } from "zod";
const Signup = z
.object({
password: z.string().min(8),
confirm: z.string(),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
const result = Signup.safeParse({
password: "correct-horse",
confirm: "correct-hose",
});
if (!result.success) {
for (const issue of result.error.issues) {
console.log(issue.path.join("."), issue.message);
}
}
// confirm Passwords do not matchThe path option matters here. Without it, the issue has an empty path, so it belongs to the object as a whole. A form library would then have no field to attach it to. Setting path: ["confirm"] makes the error appear next to the confirmation input.
The type of Signup after refine is still the same object type. z.infer gives { password: string; confirm: string }.
When the rule runs
Refinements run in order after the schema they are attached to. The following diagram shows the flow for the Signup schema.
This has a practical consequence. If password is too short, the user sees only the length error. The mismatch error appears after they fix the length. This is usually fine, since there is little point comparing a value that is already invalid. It does surprise people who expect all errors at once.
Several refine calls on the same schema all run in order, and each failing one adds an issue. Chain them when the rules are independent.
import { z } from "zod";
const Password = z
.string()
.min(8)
.refine((s) => /[A-Z]/.test(s), "Needs an uppercase letter")
.refine((s) => /\d/.test(s), "Needs a digit");
const result = Password.safeParse("lowercaseonly");
if (!result.success) {
console.log(result.error.issues.map((i) => i.message));
}
// [ 'Needs an uppercase letter', 'Needs a digit' ]Several issues from one check with superRefine
A refine callback produces at most one issue, with one message and one path. When one check should report several problems, or different codes and paths, use superRefine. It gives you a context object, and you call ctx.addIssue as many times as you need.
import { z } from "zod";
const Booking = z
.object({
start: z.coerce.date(),
end: z.coerce.date(),
guests: z.number().int().positive(),
rooms: z.number().int().positive(),
})
.superRefine((value, ctx) => {
if (value.end <= value.start) {
ctx.addIssue({
code: "custom",
message: "End must be after start",
path: ["end"],
});
}
if (value.guests > value.rooms * 4) {
ctx.addIssue({
code: "custom",
message: "At most 4 guests per room",
path: ["guests"],
});
}
});
const result = Booking.safeParse({
start: "2026-12-10",
end: "2026-12-01",
guests: 9,
rooms: 2,
});
if (!result.success) {
for (const issue of result.error.issues) {
console.log(issue.path.join("."), "-", issue.message);
}
}
// end - End must be after start
// guests - At most 4 guests per roomOne superRefine reports both problems in a single pass. With two separate refine calls you would get the same result. Prefer superRefine when the checks share setup work, or when the issues need different codes.
Newer Zod 4 releases mark superRefine as deprecated in favor of a richer refine or check API. Existing code keeps working. Check the documentation for the version you install.
Rules that need a lookup: async refinements
The callback may return a promise. This suits rules that need a database or network call, such as checking that a username is free.
import { z } from "zod";
const taken = new Set(["admin", "root"]);
async function isAvailable(name: string): Promise<boolean> {
await Promise.resolve(); // stands in for a database query
return !taken.has(name);
}
const Username = z
.string()
.min(3)
.refine(isAvailable, { message: "Username is taken" });
async function main() {
const ok = await Username.safeParseAsync("alice");
const bad = await Username.safeParseAsync("admin");
console.log(ok.success, bad.success); // true false
}
main();Once any rule in a schema is async, you must call parseAsync or safeParseAsync. The synchronous parse throws an error saying that an async refinement was encountered.
Refine, transform, and ordering
Refinements check the value without changing it. If you add a transform afterward, later rules see the transformed value. Put the rule where the value has the shape you want to check.
import { z } from "zod";
const Port = z
.string()
.transform((s) => Number(s))
.refine((n) => Number.isInteger(n) && n >= 1 && n <= 65535, {
message: "Port must be an integer from 1 to 65535",
});
console.log(Port.parse("8080")); // 8080Here the refine callback receives a number, because the transform ran first. Chapter on transforms covers this in detail. For plain string-to-number conversion, z.coerce.number() with built-in checks is simpler.
Gotchas
- Composition after refine. A refined object schema is not always a plain object schema. In Zod 3 it becomes a
ZodEffectswrapper withoutextend,pick,omit, orpartial. Zod 4 restricts some of these as well. Build the shape first, derive variants withpickorextend, and applyrefinelast. - Throwing inside the callback. If your function throws,
safeParsethrows too. Returnfalseor add an issue instead. Handle expected failures, such as a failed network call, inside the callback. - Side effects. Zod may run a refinement more than once in some schema shapes, for example inside unions. Keep callbacks free of side effects.
- Narrowing. A refine callback returning a boolean does not change the inferred type. If you want a narrower type, use a transform that returns the narrowed value, or a type guard where your Zod version supports one.
- Prefer built-ins.
z.string().min(3)produces a specific issue code that tools can inspect. Arefinewith the same logic produces onlycustom. Userefinefor what the built-ins cannot express.
Choosing the right tool
| Situation | Use |
|---|---|
| One value, one rule, one message | `refine` on that schema |
| Two fields must agree | `refine` on the object with `path` |
| One check, several different issues | `superRefine` with `ctx.addIssue` |
| Rule needs a database or API | `refine` with an async function and `safeParseAsync` |
| A built-in check already exists | The built-in (`min`, `email`, `regex`) |
Exercises
Exercise
A schema is z.object({ min: z.number(), max: z.number() }). Add a rule that fails when min is greater than max, and report the error on the max field with the message "max must be at least min". Write the schema.
Show answer
const Range = z.object({ min: z.number(), max: z.number() }).refine((r) => r.min <= r.max, { message: "max must be at least min", path: ["max"] });
Exercise
A user submits a signup form with a 5-character password and a different confirmation value. The schema is the Signup example from this chapter, with password: z.string().min(8) and a refine comparing the two fields. How many issues does safeParse return, and why?
Show answer
One issue, the "too short" error on password. The object refine runs only after every field passes its own schema, so the mismatch check is skipped until the password is long enough.
Exercise
You add an async refine to a username schema and call Username.parse("alice"). What happens, and what should you call instead?
Show answer
Zod throws an error because an async refinement was encountered during a synchronous parse. Call await Username.parseAsync("alice") or await Username.safeParseAsync("alice").