Advanced React 02 · Forms
Validating data with Zod
Why types aren’t enough for outside data, a schema line by line, types from the schema, rules and messages, errors for a form and checking server responses.
Loading lesson…
Advanced React 02 · Forms
Why types aren’t enough for outside data, a schema line by line, types from the schema, rules and messages, errors for a form and checking server responses.
Loading lesson…
From lessons TypeScript 01 and TypeScript 02 you know that a type guards what data the code expects. But types have one property that's easy to forget: they exist only while you write the code. Before the code runs, TypeScript deletes them. Look what then happens with data from a server:
interface User {name: stringage: number}async function loadUser() {const res = await fetch('/api/user') // ask the server for a user (lesson JavaScript 07)const user = (await res.json()) as User // ❌ "trust me, it's a User"return user.name.toUpperCase() // the name in capitals}
The code passes TypeScript without a single error. And now the server sends this:
{ "name": null, "age": "30" }
as User is just a promise. TypeScript has no way to check it – the data arrives only at runtime, when there are no types any more.user.name is null, and null.toUpperCase() fails with "Cannot read properties of null". The page stops working.age is the text "30", not a number. The calculation user.age + 1 gives "301" and nobody notices at once.A form is the same: everything comes from FormData as text (lesson Advanced React 01), and the user can type anything. Such data has to be checked at runtime. By hand it would look like this – and that's only two fields:
function isUser(data: unknown): data is User { // a type guard from lesson TypeScript 02return (typeof data === 'object' && data !== null &&'name' in data && typeof data.name === 'string' && data.name.length >= 2 &&'age' in data && typeof data.age === 'number' && data.age >= 18)}// …plus messages telling the user what's wrong, and the User type still separate
Zod is a library in which you describe the shape of the data once – as a schema – and get everything from it at once: a runtime check, clear messages and a type for TypeScript. You add it to a project with npm install zod.
import { z } from 'zod'// 1. The schema: how the data should look (and what to say when it doesn't)const UserSchema = z.object({name: z.string().min(2, 'The name must have at least 2 characters'),age: z.number().min(18, 'You must be at least 18'),})// 2. A type for free – no need to write it separatelytype User = z.infer<typeof UserSchema>// 3. Checking data from outside: safeParse returns either the checked data or a list of errorsasync function loadUser(): Promise<User | null> {const res = await fetch('/api/user')const result = UserSchema.safeParse(await res.json())if (!result.success) return null // the data doesn't fit → the page doesn't crash, we know itreturn result.data // here name is surely text and age a number}// (sections 1 and 2 take every line apart – for now just see how short it is)
Picture a country with customs. Everything coming from outside is checked against a list: what may be brought in and how much. What doesn't pass stays at the border – with a note saying why. Inside the country the goods aren't checked again, because they passed the border.
The borders in an app are the places where data comes in from outside. The table shows the most common ones:
| Where the data comes from | Why not trust it | Check with Zod? |
|---|---|---|
| a form (FormData) | everything is text, the user types anything | ✅ yes |
| a server response (fetch) | the server changes, fails, sends something else | ✅ yes |
| browser storage (localStorage) | an old version of the data, or nothing, may be there | ✅ yes |
| the page address (?page=2) | the user can rewrite it | ✅ yes |
| data your own code created | TypeScript guards it | ❌ no |
First, where things live in a project. You put the schema in its own file and export it (lesson JavaScript 08), because several places usually need it. At the border – where the data comes in – you import it and call safeParse:
src/├─ schemas/│ └─ user.ts ← the schema and the type from it (export) – sections 1 to 3├─ api.ts ← loading from the server: safeParse of the response – section 5└─ components/└─ SignupForm.tsx ← a form: safeParse in the action – section 4
import { z } from 'zod' // z = the whole library in one object// ─── 1. HOW THE DATA SHOULD LOOK (the schema) – the schemas file// Blanks to fill in: field (the field's name), type (string, number…), rule (min, max…) and valueexport const MySchema = z.object({field: z.type().rule(value, 'the message when the rule fails'),})// ─── 2. THE CHECK AT THE BORDER (safeParse) – where the data comes in// (in a form's action, in a function that loads from the server…); you import the schema thereconst result = MySchema.safeParse(outsideData) // outsideData = anything (unknown)// ─── 3. WHAT TO DO WITH THE RESULT ───────────────────────// doSomething and showErrors = made-up functions "work with the data" and "show the errors"if (result.success) {doSomething(result.data) // the data passed – and has the right type} else {showErrors(result.error.issues) // a list of what's wrong (field + message)}
Three questions come with every schema:
safeParse.// the file src/schemas/user.tsimport { z } from 'zod'export const UserSchema = z.object({name: z.string().trim().min(2, 'The name must have at least 2 characters'), // text, no spaces around, at least 2 charactersemail: z.email('Invalid e-mail'), // text shaped like an e-mailage: z.number().int('The age must be a whole number').min(18, 'You must be at least 18'),})// Trying it out: data that would otherwise come from outside is written by hand here// (in an app it would be a form's content or a server's response)const result = UserSchema.safeParse({ name: 'A', email: 'anna', age: 30 })result.success // falseresult.error.issues // [// { path: ['name'], message: 'The name must have at least 2 characters', … },// { path: ['email'], message: 'Invalid e-mail', … },// ]
What happens during safeParse:
path (which field – an array of names, for nested data say ['address', 'city']) and message (your message).{ success: true, data }, where data is the checked (and adjusted – trimmed of spaces, say) data. Otherwise { success: false, error }.The result is a discriminated union from TypeScript 02: by success TypeScript knows whether you may touch data or error.
What you see: The UserSchema schema from the example and four sets of sample data, as if they came from outside. Below the data is the result of safeParse.
Try it:
User type uses it safely."30" in quotes isn't a number – Zod spots it, even though it looks the same.The takeaway: A schema is a customs officer: what doesn't match the list doesn't pass – and you know exactly why.
Loading the interactive part…
Without Zod you'd write the rules into a check and the shape of the data once more into an interface. Two places that must match – and one day they drift apart (you add a field to the type and forget the check). With Zod the schema is the single source of truth (the one place where the shape of the data is written down) and the type is derived from it:
// the file src/schemas/user.ts – the type right below the schema, both exportedexport const UserSchema = z.object({name: z.string(),age: z.number(),nickname: z.string().optional(), // an optional field})export type User = z.infer<typeof UserSchema>// = { name: string; age: number; nickname?: string | undefined }// another file: import type { User } from './schemas/user'function greet(user: User) { … } // the type changes by itself when you change the schema
typeof UserSchema is the type of the schema itself, and z.infer<…> pulls out of it the type of the data that passes the schema. After a successful safeParse, result.data has exactly this type.
A schema is made of types and rules. Rules are chained with a dot and each can take a message as its last argument. The table is an index of the most common ones; what you want on the left, the code in the middle:
| I want… | Code | Note |
|---|---|---|
| text with a length | z.string().min(2, '…').max(50, '…') | the number of characters |
| text without spaces around | z.string().trim() | changes the data – trim runs before the other rules |
| an e-mail | z.email('Invalid e-mail') | also z.url() |
| text by a pattern | z.string().regex(/^[A-Z]{2}\d{4}$/, 'Invalid code') | a regular expression from lesson Advanced React 01 |
| a whole number in a range | z.number().int().min(1).max(10) | |
| a number from a form (it’s text) | z.coerce.number('Must be a number') | turns "30" into 30 |
| yes/no | z.boolean() | |
| one of the options | z.enum(['S', 'M', 'L']) | the type will be S | M | L |
| an optional field | z.string().optional() | may be missing |
| a default value | z.string().default('en') | filled in when missing |
| an array of items | z.array(UserSchema) | every item is checked |
z.coerce deserves a special mention. The age arrives from a form as the text "30" and z.number() would reject it. z.coerce.number() first calls Number("30") and only then checks the result. But an empty field becomes Number("") = 0 – so for required numbers add a rule like .min(1).
Some rules concern several fields at once – "password again must match the password". That's what refine on the whole object is for:
// in the schemas file – refine is attached after z.object({ … })export const PasswordSchema = z.object({password: z.string().min(8, 'The password must have at least 8 characters'),confirm: z.string(),}).refine((d) => d.password === d.confirm, { // d = the whole object; return true when it's finemessage: 'The passwords don’t match',path: ['confirm'], // which field the error shows at})
refine runs only once the rules of the individual fields have passed. path decides which field the message belongs to – without it, it would belong to the whole form.
A form needs errors split by field: "this at the e-mail, that at the password". That's exactly what z.flattenError returns:
// a piece of a form's action – the whole example is right belowconst result = SignupSchema.safeParse(data)if (!result.success) {const { fieldErrors } = z.flattenError(result.error)// fieldErrors = { email: ['Invalid e-mail'], confirm: ['The passwords don’t match'] }}
For each field there's an array of messages (one form field can break several rules); you usually show the first: fieldErrors.email?.[0] (?.[0] = "the first item, if the array exists"). Combined with the action from Advanced React 01, that gives a form as it's written in practice:
// the file src/components/SignupForm.tsximport { useActionState } from 'react'import { z } from 'zod'import { SignupSchema } from '../schemas/signup' // a schema with a name and an e-mail (a file like in section 6)// What the action returns: errors by field, the filled-in values, or a success messageinterface State {errors?: { name?: string[]; email?: string[] }values?: { name: string; email: string }message?: string}// ① THE ACTION – called after the form is submitted (lesson Advanced React 01)async function signup(_prev: State, formData: FormData): Promise<State> {const raw = Object.fromEntries(formData) // { name: '…', email: '…' } – all textconst result = SignupSchema.safeParse(raw) // customs at the borderif (!result.success) {return {errors: z.flattenError(result.error).fieldErrors, // errors by fieldvalues: { name: String(raw.name ?? ''), email: String(raw.email ?? '') }, // so the fields are refilled}}await registerUser(result.data) // result.data has the right type and shape (registerUser = a made-up server)return { message: 'Done' }}// ② THE COMPONENT – the form that uses the action and shows errors at the fieldsexport function SignupForm() {const [state, formAction] = useActionState(signup, {})return (<form action={formAction} noValidate><label>Name<input name="name" defaultValue={state.values?.name} /></label>{state.errors?.name && <p className="field-error">{state.errors.name[0]}</p>} {/* the field's first message */}<label><input name="email" defaultValue={state.values?.email} /></label>{state.errors?.email && <p className="field-error">{state.errors.email[0]}</p>}<button>Sign up</button>{state.message && <p>{state.message}</p>}</form>)}
Object.fromEntries(formData) turns FormData into an ordinary object { field name: value } (JavaScript 03). The underscore in _prev is just a habit: it says "I get this parameter but don't use it" – the action has to accept it, because FormData comes second. The component below the action then shows the first message from state.errors at each field.
What you see: A sign-up form. All the rules are in the SignupSchema schema; the action just calls safeParse and returns the errors by field to the form. The noValidate attribute turns off the browser's bubbles so you can see the Zod check.
Try it:
path in refine did that.@taken.com. The schema passes, but the error comes from the server – the action returns it at the e-mail.The takeaway: The rules are in one place, the action has a few lines and the errors show at the fields they concern.
Loading the interactive part…
The second big border. You check a server's response the same way – and instead of the page crashing, you show a clear error:
// the file src/api.ts – functions that talk to the serverimport { z } from 'zod'const UsersSchema = z.array(z.object({ id: z.number(), name: z.string(), email: z.email() }),)export async function loadUsers() {const res = await fetch('/api/users')const result = UsersSchema.safeParse(await res.json()) // res.json() returns unknown dataif (!result.success) {console.error(z.prettifyError(result.error)) // a readable list of errors for developersthrow new Error('The server sent data in an unexpected shape')}return result.data // type: { id; name; email }[]}// the file with a component – loading through TanStack Query (lesson Advanced React 08):// import { loadUsers } from '../api'// const { data: users } = useQuery({ queryKey: ['users'], queryFn: loadUsers })
z.prettifyError turns the errors into text that reads well in the browser console. You then call loadUsers in an effect (the recipe from Hooks 01) or in a data fetching library (Advanced React 08) – and in both cases you already know the data has the right shape.
This section puts the lesson together into steps to come back to when you check your own data. You'll find the same pattern in the Cheat sheets on the React tab.
z.infer; don't write it separately.// the file src/schemas/signup.tsimport { z } from 'zod'// 1. THE SCHEMA – what the data should look like and what to say when it doesn'texport const SignupSchema = z.object({name: z.string().trim().min(2, 'The name must have at least 2 characters'), // text without spaces around, at least 2 charactersemail: z.email('Invalid e-mail'), // text shaped like an e-mail// a form sends text → coerce turns it into a number; int = a whole numberage: z.coerce.number('The age must be a number').int().min(18, 'You must be at least 18'),password: z.string().min(8, 'The password must have at least 8 characters'),confirm: z.string(), // the password again})// 2. A RULE FOR TWO FIELDS – d = the whole object; the error shows at the confirm field.refine((d) => d.password === d.confirm, { message: 'The passwords don’t match', path: ['confirm'] })// 3. THE TYPE FROM THE SCHEMA – not written separatelyexport type SignupValues = z.infer<typeof SignupSchema>// 4. THE CHECK AT THE BORDER – in another file, say in a form's action (the whole example in section 4)://// import { SignupSchema } from '../schemas/signup'//// async function signup(_prev: State, formData: FormData): Promise<State> {// const result = SignupSchema.safeParse(Object.fromEntries(formData)) // FormData → an object → the check// if (!result.success) return { errors: z.flattenError(result.error).fieldErrors } // errors by field// await registerUser(result.data) // result.data has the type SignupValues (registerUser = a made-up server)// return { message: 'Done' }// }
as.z.infer, not written separately.z.coerce.number().refine with a path.safeParse, not parse, and errors show at the fields.Two rules for a finished schema: the e-mail and the password's length.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The challenge combines sections 3 and 4: rules in the schema, turning text into a number, a rule for two fields and errors by field in an action. For the schema, first tell yourself: how the data should look, what I say when it doesn't, and where the border is.
The form is finished; the rules are missing. Everything the sign-up should guard belongs in one schema. What exactly should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
as is just a promise.safeParse checks it and returns either the data or a list of errors.z.coerce.number() for numbers, refine with path for several fields, z.flattenError(…).fieldErrors for errors at the fields.z)z – from the library zod: a library for checking data against a schema (lesson Advanced React 02).row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).z)z – from the library zod: a library for checking data against a schema (lesson Advanced React 02).row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).