Composing and Refining Schemas
Build complex schemas with refine, transform, and unions.
Schemas Compose
Zod schemas are composable building blocks. You can refine, transform, extend, and combine them to model complex validation rules.
import { z } from "zod";
const base = z.object({ name: z.string() });
// We will add rules and combine schemas from here.Custom Rules With refine
.refine adds a custom validation predicate with an error message, for rules Zod has no built-in for.
import { z } from "zod";
const password = z.string().refine(
(s) => s.length >= 8,
{ message: "Must be at least 8 characters" }
);
// password.parse("short") throws with that message.All lessons in this course
- Zod Schema Basics
- Inferring Types from Schemas
- parse vs safeParse
- Composing and Refining Schemas