Automated summary
This skill provides schema validation patterns for Zod 4, including breaking changes from Zod 3.
Strengths
- Covers key breaking changes between Zod 3 and Zod 4
- Provides concrete examples for basic schemas, objects, unions, and transformations
- Includes error handling and custom validations with refine and superRefine
Limitations
- Does not cover all Zod 4 features exhaustively
- Assumes prior knowledge of TypeScript and schema validation
- Examples are in English only
Use this skill when migrating from Zod 3 to Zod 4 or when starting a new project with Zod 4 and TypeScript.
Avoid this skill if you are still using Zod 3 or if you are working with a different validation library like Yup or Joi.
Security analysis
SafeThe skill is a documentation guide for Zod 4 schema validation with code examples. There are no executable commands, network requests, or destructive actions. It is purely informational and safe.
No concerns found
How this analysis is madeExamples
Create a Zod 4 schema for an object with an email field (validated as email) and a password field (min 8 chars, must contain uppercase letter and number). Include custom error messages.What are the main breaking changes between Zod 3 and Zod 4 for string validations like email, uuid, url, and nonempty? Show me the old and new syntax.Define a Zod 4 discriminated union for an API response that can be either success (with data) or error (with error message).name: zod-4 description: > Zod 4 schema validation patterns. Trigger: When using Zod for validation - breaking changes from v3. license: Apache-2.0 metadata: version: '1.0'
Breaking Changes from Zod 3
// ❌ Zod 3 (OLD)
z.string().email();
z.string().uuid();
z.string().url();
z.string().nonempty();
z.object({ name: z.string() }).required_error('Required');
// ✅ Zod 4 (NEW)
z.email();
z.uuid();
z.url();
z.string().min(1);
z.object({ name: z.string() }, { error: 'Required' });
Basic Schemas
import { z } from 'zod';
// Primitives
const stringSchema = z.string();
const numberSchema = z.number();
const booleanSchema = z.boolean();
const dateSchema = z.date();
// Top-level validators (Zod 4)
const emailSchema = z.email();
const uuidSchema = z.uuid();
const urlSchema = z.url();
// With constraints
const nameSchema = z.string().min(1).max(100);
const ageSchema = z.number().int().positive().max(150);
const priceSchema = z.number().min(0).multipleOf(0.01);
Object Schemas
const userSchema = z.object({
id: z.uuid(),
email: z.email({ error: 'Invalid email address' }),
name: z.string().min(1, { error: 'Name is required' }),
age: z.number().int().positive().optional(),
role: z.enum(['admin', 'user', 'guest']),
metadata: z.record(z.string(), z.unknown()).optional()
});
type User = z.infer<typeof userSchema>;
// Parsing
const user = userSchema.parse(data); // Throws on error
const result = userSchema.safeParse(data); // Returns { success, data/error }
if (result.success) {
console.log(result.data);
} else {
console.log(result.error.issues);
}
Arrays and Records
// Arrays
const tagsSchema = z.array(z.string()).min(1).max(10);
const numbersSchema = z.array(z.number()).nonempty();
// Records (objects with dynamic keys)
const scoresSchema = z.record(z.string(), z.number());
// { [key: string]: number }
// Tuples
const coordinatesSchema = z.tuple([z.number(), z.number()]);
// [number, number]
Unions and Discriminated Unions
// Simple union
const stringOrNumber = z.union([z.string(), z.number()]);
// Discriminated union (more efficient)
const resultSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('success'), data: z.unknown() }),
z.object({ status: z.literal('error'), error: z.string() })
]);
Transformations
// Transform during parsing
const lowercaseEmail = z.email().transform(email => email.toLowerCase());
// Coercion (convert types)
const numberFromString = z.coerce.number(); // "42" → 42
const dateFromString = z.coerce.date(); // "2024-01-01" → Date
// Preprocessing
const trimmedString = z.preprocess(
val => (typeof val === 'string' ? val.trim() : val),
z.string()
);
Refinements
const passwordSchema = z
.string()
.min(8)
.refine(val => /[A-Z]/.test(val), {
message: 'Must contain uppercase letter'
})
.refine(val => /[0-9]/.test(val), {
message: 'Must contain number'
});
// With superRefine for multiple errors
const formSchema = z
.object({
password: z.string(),
confirmPassword: z.string()
})
.superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Passwords don't match",
path: ['confirmPassword']
});
}
});
Optional and Nullable
// Optional (T | undefined)
z.string().optional();
// Nullable (T | null)
z.string().nullable();
// Both (T | null | undefined)
z.string().nullish();
// Default values
z.string().default('unknown');
z.number().default(() => Math.random());
Error Handling
// Zod 4: Use 'error' param instead of 'message'
const schema = z.object({
name: z.string({ error: 'Name must be a string' }),
email: z.email({ error: 'Invalid email format' }),
age: z.number().min(18, { error: 'Must be 18 or older' })
});
// Custom error map
const customSchema = z.string({
error: issue => {
if (issue.code === 'too_small') {
return 'String is too short';
}
return 'Invalid string';
}
});
React Hook Form Integration
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
const schema = z.object({
email: z.email(),
password: z.string().min(8),
});
type FormData = z.infer<typeof schema>;
function Form() {
const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
resolver: zodResolver(schema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} />
{errors.email && <span>{errors.email.message}</span>}
</form>
);
}
Keywords
zod, validation, schema, typescript, forms, parsing
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/download' --output '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md.part' && mv '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md.part' '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md' && test -s '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/zod-4' && cp -R '.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25' '.claude/skills/zod-4'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25'openskills read 'zod-4-schema-validation-patterns-breaking-changes-mm5t8a25'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/zod-4-schema-validation-patterns-breaking-changes-mm5t8a25/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
React Hook Form Best Practices
Development
Master React Hook Form: avoid anti-patterns, manage subscriptions, and handle reset, dirty state, and controlled inputs correctly.
Emotion to Mantine Migration
Development
Migrate Emotion styled-components to Mantine components with style props and CSS modules. Use when converting .styled.tsx files or removing @emotion imports.
Scope Creep Detector
Development
Analyzes git diffs against a stated intent to detect scope creep, unrelated files, broad PRs, and oversized changes, then suggests keep, split, or justify actions.