Sub topic 5
Describing valid data with Zod schemas
This chapter assumes you know React function components and hooks, TypeScript basics (types and generics), and how HTML forms and the submit event work. You also need to be comfortable with Promises and async/await. It covers how to describe valid data with Zod. A later chapter shows how to connect a schema to a form.
What a Zod schema is
A Zod schema is a JavaScript object that describes the shape and rules of a value. You can call its parse method with any value. If the value matches, parse returns it. If not, parse throws an error that lists every problem.
TypeScript types are erased when your code is compiled, so they cannot check data at runtime. Form input, API responses, and URL parameters all arrive at runtime, and TypeScript cannot vouch for them. A schema checks them while the program runs.
import { z } from "zod";
const emailSchema = z.string().email("Enter a valid email");
console.log(emailSchema.parse("[email protected]")); // "[email protected]"
try {
emailSchema.parse("not-an-email");
} catch (error) {
if (error instanceof z.ZodError) {
console.log(error.issues[0].message); // "Enter a valid email"
}
}Every problem is an entry in error.issues. Each issue has a message, a code such as too_small or invalid_type, and a path that points to the failing value.
Primitive schemas
Zod has one factory function for each basic type.
| Schema | Accepts |
|---|---|
| `z.string()` | Any string, including an empty one |
| `z.number()` | Numbers, but not `NaN` |
| `z.boolean()` | `true` or `false` |
| `z.date()` | `Date` objects |
| `z.enum(["a", "b"])` | One of the listed strings |
| `z.literal("yes")` | Exactly that value |
Note that z.string() accepts "". An empty text input produces an empty string, so a "required" field needs an explicit rule such as .min(1, "Email is required"). This is the most common first mistake when you validate forms.
Adding rules with chained methods
Each schema has methods that add rules. They return a new schema, so you chain them. The last argument of most methods is the error message, which a form can show to the user.
import { z } from "zod";
const usernameSchema = z
.string()
.trim()
.min(3, "Use at least 3 characters")
.max(20, "Use at most 20 characters")
.regex(/^[a-z0-9_]+$/, "Lowercase letters, digits and _ only");
const ageSchema = z
.number({ invalid_type_error: "Age must be a number" })
.int("Age must be a whole number")
.min(18, "You must be at least 18");Here trim() is a transform, not a check. It changes the value before the later rules run. So " ab " is trimmed to "ab" and then fails min(3).
The invalid_type_error option sets the message for the case where the value is not a number at all. The names of these message options differ between Zod major versions. Zod 4 uses a single error option instead. Check the documentation for the version you installed.
Building object schemas
A form is usually an object, so z.object is the schema you will use most.
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"),
newsletter: z.boolean(),
});
const result = signUpSchema.safeParse({
email: "",
password: "short",
newsletter: false,
});
if (!result.success) {
console.log(result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`));
// ["email: Email is required", "email: Enter a valid email", "password: Use at least 8 characters"]
}Several details are worth noticing.
- Zod runs every rule on a field, so an empty email produces two issues. A form normally shows only the first message for a field.
- By default, unknown keys are removed from the output. Extra data does not cause an error. Use
.strict()if you want unknown keys to fail. - A missing key fails with a type error, because
undefinedis not a string.
parse and safeParse
parse throws on failure. safeParse never throws. It returns an object with a success flag.
import { z } from "zod";
const schema = z.object({ age: z.number() });
const result = schema.safeParse({ age: "30" });
if (result.success) {
console.log(result.data.age); // typed as number
} else {
console.log(result.error.issues[0].code); // "invalid_type"
}Use safeParse for user input, because invalid input is expected and is not an exceptional event. TypeScript narrows result on the success flag, so result.data is only available in the success branch. In a form, you will rarely call either method yourself. The resolver calls safeParse for you and turns the issues into field errors.
Optional, nullable, and default values
Optional fields are a frequent source of confusion, so it helps to separate three cases.
| Method | Allowed values | Resulting type | Column |
|---|---|---|---|
| `.optional()` | The value or `undefined` | `T \ | undefined` |
| `.nullable()` | The value or `null` | `T \ | null` |
| `.default(x)` | Replaces `undefined` with `x` | `T` in the output |
An optional text input does not give you undefined. A text input that the user left blank gives "". So z.string().optional() still accepts "", but a rule such as .min(3) would reject it. To allow either a blank value or a valid one, use a union with a literal.
import { z } from "zod";
const websiteSchema = z.union([z.literal(""), z.string().url("Enter a valid URL")]);
console.log(websiteSchema.safeParse("").success); // true
console.log(websiteSchema.safeParse("https://example.com").success); // true
console.log(websiteSchema.safeParse("example").success); // falseChoices, arrays, and nested objects
Schemas compose. You can put one inside another to any depth.
import { z } from "zod";
const profileSchema = z.object({
role: z.enum(["admin", "editor", "viewer"]),
tags: z.array(z.string().min(1)).max(5, "At most 5 tags"),
address: z.object({
city: z.string().min(1, "City is required"),
postcode: z.string().min(1, "Postcode is required"),
}),
});Issue paths follow the structure. A bad city is reported at ["address", "city"], and a bad tag at ["tags", 2]. React Hook Form uses these paths to place each message on the right field, which is why nested schemas work with nested field names such as address.city.
You can reuse and adjust object schemas with .pick, .omit, .partial, and .extend. For example, signUpSchema.pick({ email: true }) makes a schema for a "forgot password" form that has only the email field.
import { z } from "zod";
const baseSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
const forgotPasswordSchema = baseSchema.pick({ email: true });
const loginSchema = baseSchema.extend({ remember: z.boolean() });Custom messages and the order of checks
Zod does not stop at the first failure within a single schema. It stops a chain early only in one case: if the base type is wrong, such as a number where a string was expected, the later rules are skipped. This is why a z.string() field that receives undefined gives one type issue, not a type issue plus a length issue.
Write messages for the user, not for developers. "Use at least 8 characters" tells the user what to do. "String must contain at least 8 character(s)" is the default text, and it is usually not what you want in the interface.
Common mistakes
- Using
z.string()alone for a required text field. It accepts an empty string, so add.min(1, "..."). - Using
z.number()for a text input. Inputs give strings, so the value fails with aninvalid_typeissue. A later chapter on transforms shows the fix. - Using
parsein a render function or an event handler without atryblock. An invalid value throws and can crash the component tree. - Expecting
.optional()to accept an empty input. It acceptsundefined, not"". - Leaving default messages in place, so users see developer wording.
Exercise
Write a Zod schema named contactSchema for a contact form. It needs a name (required, at most 50 characters), an email (required, valid format), and an optional website that is either blank or a valid URL. Then say what contactSchema.safeParse({ name: "", email: "[email protected]", website: "" }) returns.
Show answer
const contactSchema = z.object({
name: z.string().min(1, "Name is required").max(50, "Use at most 50 characters"),
email: z.string().min(1, "Email is required").email("Enter a valid email"),
website: z.union([z.literal(""), z.string().url("Enter a valid URL")]),
});
The call returns { success: false, error }. The error.issues array has one issue, with path ["name"] and message "Name is required". The email is valid and an empty website matches z.literal(""), so neither produces an issue.
Exercise
A field uses z.string().optional(), and a user leaves the text input blank. Does validation pass? Why does this matter when you add .min(3)?
Show answer
It passes, because a blank input gives "", which is a string. optional() only allows undefined. If you add .min(3), the empty string fails with a length error, so the "optional" field becomes effectively required. To allow blank or valid values, use z.union([z.literal(""), z.string().min(3)]).