Sub topic 11
Custom Rules with `refine`
This chapter assumes you know basic TypeScript types, JavaScript objects, Zod schemas, and try/catch. You should also know how to install and import an npm package.
Built-in Zod checks cover common rules such as minimum string length and numeric ranges. A refinement is a custom validation rule for a condition that Zod does not provide directly. You add one with .refine().
Validate one value
refine() receives the value after the earlier schema checks pass. It must return true for valid data and false for invalid data.
import { z } from "zod";
const Username = z
.string()
.min(3, "Username must have at least 3 characters")
.refine((value) => !value.includes(" "), {
message: "Username cannot contain spaces",
});
for (const value of ["ada", "ada lovelace", "al"]) {
const result = Username.safeParse(value);
if (result.success) {
console.log("Valid:", result.data);
} else {
console.log("Invalid:", result.error.issues[0].message);
}
}The message option controls the validation message. Use built-in checks first when they express the rule clearly. A refinement should describe the remaining business rule.
Validate related fields
A field-level rule can inspect only that field. To compare multiple fields, place refine() on an object schema.
import { z } from "zod";
const Signup = z
.object({
email: z.string().email(),
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({
email: "[email protected]",
password: "correct horse",
confirm: "correct pony",
});
if (!result.success) {
for (const issue of result.error.issues) {
console.log(`${issue.path.join(".")}: ${issue.message}`);
}
}The callback receives the parsed object. The path option associates the error with a particular field. This helps a form display the message beside confirm, even though the rule compares two fields.
How a refinement fits into parsing
Zod first checks the basic shape and built-in constraints. It then runs the refinement on data that passed those checks. This lets the callback work with the expected TypeScript shape.
Common errors
- Returning a truthy value that does not represent the rule. Return a boolean expression directly.
- Using
refine()for a standard check such as.email()or.min(). Built-in checks are clearer. - Forgetting
pathfor a cross-field form error. Without it, the issue is attached to the object itself. - Treating a refinement as a security boundary by itself. Validate every untrusted request at its boundary, then use the parsed result.
Exercise
Where should you place a refinement that checks whether startDate comes before endDate, and how can you show the error beside endDate?
Show answer
Place it on the object schema containing both fields, and set path: ["endDate"] in the refinement options.