Sub topic 5
Describing valid data with Zod schemas
This chapter assumes you know React function components and hooks, TypeScript basics such as types and generics, and how HTML form values arrive as strings. You do not need to know React Hook Form's resolver yet. That comes in a later chapter.
What a Zod schema is
Zod is a TypeScript library for describing the shape of valid data. A schema is a value you build once and then use to check data at runtime. Plain TypeScript types disappear when your code is compiled, so they cannot check what a user typed into a form. A Zod schema exists at runtime, so it can.
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});Each key in z.object names a field. Each value is a schema for that field. The optional string passed to a rule is the error message shown when that rule fails.
Building blocks
| Schema | Accepts | Common rules |
|---|---|---|
| `z.string()` | Text | `.min()`, `.max()`, `.email()`, `.regex()` |
| `z.number()` | Numbers | `.min()`, `.max()`, `.int()` |
| `z.boolean()` | `true` or `false` | none needed |
| `z.array(item)` | A list of `item` values | `.min()`, `.max()` |
| `z.object({...})` | An object with set keys | nesting other schemas |
Rules chain from left to right. A field fails with the message of the first rule that breaks. z.string().min(1, "Email is required").email(...) is the usual way to treat an empty input as "required". An empty string is still a valid string, so .min(1) is what rejects it.
Checking data with safeParse
Call safeParse to test a value without throwing an exception.
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
const result = signUpSchema.safeParse({ email: "", password: "abc" });
if (result.success) {
console.log(result.data.email);
} else {
for (const issue of result.error.issues) {
console.log(issue.path.join("."), "-", issue.message);
}
}The result is one of two shapes. On success, result.data holds the checked value. On failure, result.error.issues lists every problem. Each issue has a path to the failing field and a message. Running the code above prints email - Email is required and password - Use at least 8 characters.
This list of paths and messages is what zodResolver will later turn into formState.errors.
Common mistakes
- Forgetting
.min(1)on required text fields. An empty input passesz.string()alone. - Putting the message in the wrong place. Pass it as the rule's argument, such as
.min(8, "Too short"). - Using
parseinstead ofsafeParsein UI code.parsethrows on bad data, so you must wrap it intry/catch.
Exercise
Write a schema for an object with a username string of at least 3 characters and an age number that is a whole number of at least 18. Then say what safeParse({ username: "al", age: 17.5 }) reports.
Show answer
const schema = z.object({ username: z.string().min(3), age: z.number().int().min(18) }); The call returns success: false. The issues list has two entries: one at path "username" because "al" is shorter than 3 characters, and one at path "age" because 17.5 is not an integer (and is also below 18).