Next.js course ยท Module 6: Forms and Server Actions
Form Validation with Zod
In this lesson11
In Quantum Metropolis, every system requires precise data validation - from access terminals to implant control panels. Zod is a validation library designed with TypeScript in mind that has become the standard in the Next.js ecosystem. Unlike other solutions, Zod automatically generates TypeScript types from validation schemas, eliminating code duplication.
Why Zod?
In the year 2150, Quantum Metropolis systems require reliable data validation. Zod stands out from other validation libraries (Yup, Joi) for several reasons:
- TypeScript-first - Zod schemas automatically generate types, eliminating duplication
- Zero dependencies - lightweight library (~10 KB gzipped)
- Next.js standard - officially recommended in Next.js documentation
- Works on server and client - ideal for Server Actions
Installation and Import
npm install zodimport { z } from 'zod';Basic Zod Schemas
Zod offers a set of methods for defining data types - like digital DNA describing the structure of information in the system:
import { z } from 'zod';
// Primitive types
const nameSchema = z.string();
const ageSchema = z.number();
const isActiveSchema = z.boolean();
// Object schema - we combine types into a structure
const userSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().positive(),
isActive: z.boolean(),
});Each z.string(), z.number(), z.boolean() is a basic building block of a schema. The z.object() method combines them into a comprehensive structure - like a terminal schema in Quantum Metropolis.
Validation Methods: parse and safeParse
Zod offers two ways to validate data:
import { z } from 'zod';
const schema = z.object({
name: z.string().min(2),
email: z.string().email(),
});
// 1. parse() - throws an exception for invalid data
try {
const data = schema.parse({ name: "Neo", email: "neo@quantum.io" });
console.log("Valid data:", data);
} catch (error) {
console.error("Validation error:", error);
}
// 2. safeParse() - does NOT throw, returns a result object
const result = schema.safeParse({ name: "", email: "bad-email" });
if (result.success) {
console.log("Data:", result.data);
} else {
console.log("Errors:", result.error.errors);
// [{ path: ["name"], message: "String must contain at least 2 character(s)" }, ...]
}Rule: Use safeParse() in forms and Server Actions (safer), and parse() when you want to fail fast on invalid data.
Error Messages and Validation Rules
Zod allows you to precisely define validation rules with custom messages - like configuring a security system on a terminal:
import { z } from 'zod';
const registrationSchema = z.object({
username: z.string()
.min(3, { message: "Username must be at least 3 characters" })
.max(20, { message: "Username can be at most 20 characters" }),
email: z.string()
.email({ message: "Invalid email address format" }),
age: z.number()
.int({ message: "Age must be a whole number" })
.min(13, { message: "You must be at least 13 years old" }),
password: z.string()
.min(8, { message: "Password must be at least 8 characters" })
.regex(/[A-Z]/, { message: "Password must contain an uppercase letter" })
.regex(/[0-9]/, { message: "Password must contain a digit" }),
acceptTerms: z.boolean()
.refine(val => val === true, {
message: "You must accept the system terms of use"
}),
});The .refine() method allows you to define custom, non-standard validation rules - useful when built-in methods aren't enough.
Type Inference: z.infer
One of Zod's most powerful features is the automatic generation of TypeScript types from schemas. You don't need to maintain separate interfaces:
import { z } from 'zod';
const implantSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
powerLevel: z.number().min(0).max(100),
isActive: z.boolean(),
tags: z.array(z.string()),
});
// Type automatically generated from schema
type Implant = z.infer<typeof implantSchema>;
// Manual equivalent: { id: string; name: string; powerLevel: number; isActive: boolean; tags: string[] }
// Now type and validation are SYNCHRONIZED
function processImplant(data: Implant) {
console.log(data.name); // TypeScript knows the type!
}Thanks to z.infer, you have a single source of truth - the schema defines both validation and the TypeScript type.
Integration with React Hook Form
Zod works great with React Hook Form thanks to the zodResolver adapter. This is the most commonly encountered pattern in Next.js applications:
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// 1. Define the schema
const loginSchema = z.object({
email: z.string()
.email({ message: "Invalid email address" }),
password: z.string()
.min(8, { message: "Password must be at least 8 characters" }),
});
// 2. Generate the type
type LoginForm = z.infer<typeof loginSchema>;
// 3. Use in the component
export default function LoginPage() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting }
} = useForm<LoginForm>({
resolver: zodResolver(loginSchema), // Zod as the validator
defaultValues: { email: '', password: '' }
});
const onSubmit = async (data: LoginForm) => {
// data is already validated and typed!
console.log("Logging in:", data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email')} placeholder="Email" />
{errors.email && <p>{errors.email.message}</p>}
<input {...register('password')} type="password" placeholder="Password" />
{errors.password && <p>{errors.password.message}</p>}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Logging in...' : 'Log in'}
</button>
</form>
);
}The key line is resolver: zodResolver(loginSchema) - it connects the Zod schema with the React Hook Form validation system.
Reusable Schemas and Composition
In large applications, it's worth creating reusable schemas that can be combined and extended:
import { z } from 'zod';
// Base address schema - used in multiple places
const addressSchema = z.object({
street: z.string().min(1, "Street is required"),
city: z.string().min(1, "City is required"),
postCode: z.string().regex(/^\d{2}-\d{3}$/, "Format: XX-XXX"),
});
// User schema - extending with address
const userSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
address: addressSchema, // Nesting
shippingAddress: addressSchema.optional(), // Optional
});
// .merge() - merging two schemas
const baseProfile = z.object({ name: z.string(), bio: z.string() });
const socialProfile = z.object({ twitter: z.string(), github: z.string() });
const fullProfile = baseProfile.merge(socialProfile);
// .extend() - adding fields to an existing schema
const adminUser = userSchema.extend({
role: z.literal('admin'),
permissions: z.array(z.string()),
});
type AdminUser = z.infer<typeof adminUser>;Advanced Techniques: refine and superRefine
The .refine() method allows validation that can't be expressed declaratively - e.g. comparing two fields:
import { z } from 'zod';
const passwordSchema = z.object({
password: z.string().min(8),
confirmPassword: z.string(),
}).refine(data => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"], // Error assigned to confirmPassword field
});
// superRefine - when you need multiple errors simultaneously
const advancedSchema = z.object({
accountType: z.enum(['personal', 'business']),
personalId: z.string().optional(),
companyId: z.string().optional(),
}).superRefine((data, ctx) => {
if (data.accountType === 'personal' && !data.personalId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Personal ID is required for a personal account",
path: ['personalId'],
});
}
if (data.accountType === 'business' && !data.companyId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Company ID is required for a business account",
path: ['companyId'],
});
}
});Alternatives: Yup and Joi
Zod is the standard in the Next.js ecosystem, but alternatives exist:
- Yup - popular with Formik, declarative syntax, but requires manual TypeScript type definitions
- Joi - powerful, feature-rich, but large (~40 KB) and mostly server-side
Zod is recommended for Next.js projects because it combines validation with TypeScript types and works on both server and client.
Summary
Zod is an essential tool in the Next.js developer's arsenal:
z.string(),z.number(),z.object()- defining schemasparse()andsafeParse()- data validation.min(),.email(),.regex()- rules with error messages.refine()- custom validationzodResolver- integration with React Hook Formz.infer<typeof schema>- automatic type generation
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Simulation of validation with Zod - schemas, parse, safeParse, error messages
// Simplified "Zod" for demonstration (in a real project you import z from the zod package)
interface ZodIssue { path: string[]; message: string }
interface ZodResult<T> { success: boolean; data?: T; error?: { issues: ZodIssue[] } }
const z = {
string: () => {
const rules: Array<{ type: string; value?: any; msg: string }> = [];
const validator: any = {
min(n: number, opt?: { message?: string }) { rules.push({ type: 'min', value: n, msg: opt?.message || `Min ${n} characters` }); return validator; },
max(n: number, opt?: { message?: string }) { rules.push({ type: 'max', value: n, msg: opt?.message || `Max ${n} characters` }); return validator; },
email(opt?: { message?: string }) { rules.push({ type: 'email', msg: opt?.message || 'Invalid email' }); return validator; },
regex(re: RegExp, opt?: { message?: string }) { rules.push({ type: 'regex', value: re, msg: opt?.message || 'Invalid format' }); return validator; },
_validate(val: string): string | null {
if (typeof val !== 'string') return 'String is required';
for (const rule of rules) {
if (rule.type === 'min' && val.length < rule.value) return rule.msg;
if (rule.type === 'max' && val.length > rule.value) return rule.msg;
if (rule.type === 'email' && !/\S+@\S+\.\S+/.test(val)) return rule.msg;
if (rule.type === 'regex' && !rule.value.test(val)) return rule.msg;
}
return null;
},
};
return validator;
},
coerce: {
number: () => {
const rules: Array<{ type: string; value?: any; msg: string }> = [];
const validator: any = {
min(n: number, opt?: { message?: string }) { rules.push({ type: 'min', value: n, msg: opt?.message || `Min ${n}` }); return validator; },
max(n: number, opt?: { message?: string }) { rules.push({ type: 'max', value: n, msg: opt?.message || `Max ${n}` }); return validator; },
int(opt?: { message?: string }) { rules.push({ type: 'int', msg: opt?.message || 'An integer is required' }); return validator; },
_validate(val: string): string | null {
const num = Number(val);
if (val === '' || isNaN(num)) return 'A number is required';
for (const rule of rules) {
if (rule.type === 'min' && num < rule.value) return rule.msg;
if (rule.type === 'max' && num > rule.value) return rule.msg;
if (rule.type === 'int' && !Number.isInteger(num)) return rule.msg;
}
return null;
},
};
return validator;
},
},
object: (shape: Record<string, any>) => ({
safeParse(data: Record<string, string>): ZodResult<any> {
const issues: ZodIssue[] = [];
const parsed: any = {};
for (const [key, validator] of Object.entries(shape)) {
const err = validator._validate(data[key] || '');
if (err) issues.push({ path: [key], message: err });
else parsed[key] = data[key];
}
if (issues.length > 0) return { success: false, error: { issues } };
return { success: true, data: parsed };
},
parse(data: Record<string, string>) {
const result = this.safeParse(data);
if (!result.success) throw new Error('Zod validation failed: ' + result.error!.issues.map(i => i.message).join(', '));
return result.data;
},
}),
};
// --- ZOD SCHEMA ---
// In a real project z comes from the zod package
const implantSchema = z.object({
name: z.string()
.min(2, { message: 'Name must have at least 2 characters' })
.max(50, { message: 'Name can have at most 50 characters' }),
email: z.string()
.email({ message: 'Invalid email format' }),
powerLevel: z.coerce.number()
.min(1, { message: 'Power level must be greater than 0' })
.max(100, { message: 'Power level cannot exceed 100' }),
});
// type Implant = z.infer<typeof implantSchema>;
export default function ZodValidationDemo() {
const [values, setValues] = useState({ name: '', email: '', powerLevel: '' });
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [result, setResult] = useState<{ type: 'success' | 'error'; data: string } | null>(null);
const [mode, setMode] = useState<'safeParse' | 'parse'>('safeParse');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
setFieldErrors({});
setResult(null);
if (mode === 'safeParse') {
const res = implantSchema.safeParse(values);
if (res.success) {
setResult({ type: 'success', data: JSON.stringify(res.data, null, 2) });
} else {
const errs: Record<string, string> = {};
for (const issue of res.error!.issues) {
errs[issue.path[0]] = issue.message;
}
setFieldErrors(errs);
setResult({ type: 'error', data: JSON.stringify(res.error!.issues, null, 2) });
}
} else {
try {
const data = implantSchema.parse(values);
setResult({ type: 'success', data: JSON.stringify(data, null, 2) });
} catch (err: any) {
setResult({ type: 'error', data: err.message });
}
}
};
const inputStyle: React.CSSProperties = {
width: '100%', padding: '10px', background: '#0d1117',
border: '1px solid #333', borderRadius: 6, color: '#e0e0e0',
fontFamily: 'monospace', fontSize: 13, boxSizing: 'border-box'
};
const schemaCode = `const implantSchema = z.object({
name: z.string().min(2).max(50),
email: z.string().email(),
powerLevel: z.coerce.number().min(1).max(100),
});
type Implant = z.infer<typeof implantSchema>;`;
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Validation with Zod</h1>
<p style={{ color: '#888', fontSize: 13, marginBottom: 12 }}>
Test the Zod schema - enter data and choose a validation method.
</p>
<pre style={{ background: '#0d1117', border: '1px solid #333', borderRadius: 8, padding: 12, fontSize: 11, color: '#ce93d8', marginBottom: 16 }}>
{schemaCode}
</pre>
<div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
{(['safeParse', 'parse'] as const).map(m => (
<button key={m} onClick={() => { setMode(m); setResult(null); setFieldErrors({}); }} style={{
background: mode === m ? '#1565c0' : '#1a2744',
color: '#fff', border: `1px solid ${mode === m ? '#64ffda' : '#333'}`,
borderRadius: 6, padding: '6px 14px', cursor: 'pointer', fontFamily: 'monospace', fontSize: 12
}}>
schema.{m}()
</button>
))}
</div>
<form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
{(['name', 'email', 'powerLevel'] as const).map(field => (
<div key={field} style={{ marginBottom: 12 }}>
<label style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>
{field}
</label>
<input
value={values[field]}
onChange={e => setValues(prev => ({ ...prev, [field]: e.target.value }))}
placeholder={field === 'powerLevel' ? '1-100' : field === 'email' ? 'neo@quantum.io' : 'Neural Link'}
style={{ ...inputStyle, borderColor: fieldErrors[field] ? '#f44336' : '#333' }}
/>
{fieldErrors[field] && <div style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{fieldErrors[field]}</div>}
</div>
))}
<button type="submit" style={{
background: '#e91e63', color: '#fff', border: 'none', borderRadius: 6,
padding: '10px 20px', cursor: 'pointer', fontFamily: 'monospace', width: '100%'
}}>
schema.{mode}(formData)
</button>
</form>
{result && (
<div style={{
marginTop: 16, borderRadius: 8, padding: 12, maxWidth: 400,
background: result.type === 'success' ? '#1b5e20' : '#3e1010',
border: `1px solid ${result.type === 'success' ? '#4caf50' : '#f44336'}`
}}>
<div style={{ color: result.type === 'success' ? '#4caf50' : '#f44336', marginBottom: 4 }}>
{result.type === 'success' ? 'Validation successful! Typed result:' : mode === 'parse' ? 'parse() threw an exception:' : 'safeParse() returned errors:'}
</div>
<pre style={{ color: '#ccc', fontSize: 11, margin: 0, whiteSpace: 'pre-wrap' }}>{result.data}</pre>
</div>
)}
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How does safeParse() differ from parse() in Zod?
Hands-on tasks in the game
- Code editor
Create a Zod schema with field validation (name, email, powerLevel) and integrate it with React Hook Form via zodResolver
- Vertical ordering
Arrange the steps for integrating Zod with React Hook Form in the correct order
- Click in order
Arrange the Zod library import syntax
- Code editor
Create a contact form with fields: name, email, message using controlled components and useState