### Install Zod Mini Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx How to install Zod Mini, which is part of the Zod package. ```sh npm install zod@^4.0.0 ``` -------------------------------- ### New transformer syntax Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/MIGRATION.md Example of the new `.transform()` method available on all Zod schemas. ```typescript z.string().transform((val) => val.length); ``` -------------------------------- ### Install Zod Stable Version Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/home.md Install the stable version of Zod using various package managers. ```shell npm install zod # npm deno add npm:zod # deno yarn add zod # yarn bun add zod # bun pnpm add zod # pnpm ``` -------------------------------- ### Installation Source: https://github.com/colinhacks/zod/blob/main/README.md Command to install Zod using npm. ```shell npm install zod ``` -------------------------------- ### Peer Dependency Configuration Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of adding Zod as a peer dependency in package.json. ```json // package.json { // ... "peerDependencies": { "zod": "^4.0.0" } } ``` -------------------------------- ### .register() Method Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of registering a schema in a registry using the .register() method. ```ts const myReg = z.registry<{title: string}>(); z.string().register(myReg, { title: "My cool string schema" }); ``` -------------------------------- ### Dev Server Source: https://github.com/colinhacks/zod/blob/main/CONTRIBUTING.md Command to start the development server for Zod documentation. ```sh pnpm run --filter=@zod/docs dev ``` -------------------------------- ### .clone() Method Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of cloning a schema using the .clone() method. ```ts const mySchema = z.string() mySchema.clone(mySchema._zod.def); ``` -------------------------------- ### Install Zod Canary Version Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/home.md Install the canary version of Zod, which is published on every commit, using various package managers. ```shell npm install zod@canary # npm deno add npm:zod@canary # deno yarn add zod@canary # yarn bun add zod@canary # bun pnpm add zod@canary # pnpm ``` -------------------------------- ### Importing Zod 4 Core Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of importing the Zod 4 core package using its permalink subpath. ```ts import * as z4 from "zod/v4/core"; ``` -------------------------------- ### .brand() Method Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of branding a schema using the .brand() method. ```ts import * as z from "zod/mini" const USD = z.string().brand("USD"); ``` -------------------------------- ### Initial Recipe schema for pick/omit examples Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx A base Zod object schema representing a recipe, used as a starting point for demonstrating .pick() and .omit() methods. ```typescript const Recipe = z.object({ title: z.string(), description: z.string().optional(), ingredients: z.array(z.string()) }); // { title: string; description?: string | undefined; ingredients: string[] } ``` -------------------------------- ### Peer and Dev Dependency Configuration Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of adding Zod as both a peer and dev dependency in package.json for development purposes. ```json // package.json { "peerDependencies": { "zod": "^4.0.0" }, "devDependencies": { "zod": "^4.0.0" } } ``` -------------------------------- ### Defining a schema Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/basics.mdx Example of defining a Zod object schema. ```ts import * as z from "zod"; const Player = z.object({ username: z.string(), xp: z.number() }); ``` ```ts import * as z from "zod/mini" const Player = z.object({ username: z.string(), xp: z.number() }); ``` -------------------------------- ### Normalized URL example Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates the output of `new URL().href` for a complex URL, showing normalization. ```ts new URL("HTTP://ExAmPle.com:80/./a/../b?X=1#f oo").href // => "http://example.com/b?X=1#f%20oo" ``` -------------------------------- ### Coercion example Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates how z.coerce.string() converts various input types to strings. ```ts const schema = z.coerce.string(); schema.parse("tuna"); // => "tuna" schema.parse(42); // => "42" schema.parse(true); // => "true" schema.parse(null); // => "null" ``` -------------------------------- ### Simple String Transforms Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of simple string transformation methods in Zod and Zod Mini. ```typescript z.string().trim(); // trim whitespace z.string().toLowerCase(); // toLowerCase z.string().toUpperCase(); // toUpperCase z.string().normalize(); // normalize unicode characters ``` ```typescript z.string().check(z.trim()); // trim whitespace z.string().check(z.toLowerCase()); // toLowerCase z.string().check(z.toUpperCase()); // toUpperCase z.string().check(z.normalize()); // normalize unicode characters ``` -------------------------------- ### Creating a ZodError Instance Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/ERROR_HANDLING.md Example of how to manually create a new instance of ZodError. ```ts import * as z from "zod"; const myError = new z.ZodError([]); ``` -------------------------------- ### Defining an array schema Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of how to define an array schema using Zod and Zod Mini. ```ts const stringArray = z.array(z.string()); // or z.string().array() ``` ```ts const stringArray = z.array(z.string()); ``` -------------------------------- ### Explicit First Push Source: https://github.com/colinhacks/zod/blob/main/AGENTS.md An example of how to explicitly push to a new remote branch to avoid accidentally pushing to `main`. ```bash ``` -------------------------------- ### Interleaving transformations and refinements Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/MIGRATION.md Demonstrates how transformations and refinements can be interleaved using the dedicated 'ZodEffects' class. ```typescript const test = z .string() .transform((val) => val.length) .refine((val) => val > 5, { message: "Input is too short" }) .transform((val) => val * 2); test.parse("12characters"); // => 24 ``` -------------------------------- ### File schemas Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/json-schema.mdx Example of `z.file()` with size and MIME checks represented in the JSON Schema. ```ts z.file().min(1).max(1024 * 1024).mime("image/png"); // => { // type: "string", // format: "binary", // contentEncoding: "binary", // contentMediaType: "image/png", // minLength: 1, // maxLength: 1048576, // } ``` -------------------------------- ### Make a schema nullable (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of making a schema nullable using Zod. ```ts z.nullable(z.literal("yoda")); // or z.literal("yoda").nullable() ``` -------------------------------- ### Simple Boolean Schema Parse Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of parsing a boolean schema with Zod Mini to demonstrate bundle size. ```ts z.boolean().parse(true) ``` -------------------------------- ### Make a schema nullable (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of making a schema nullable using Zod Mini. ```ts const nullableYoda = z.nullable(z.literal("yoda")); ``` -------------------------------- ### Traversing Zod Schemas Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/core.mdx Example of how to traverse Zod schemas using the `_zod.def` property to discriminate between types. ```ts export function walk(_schema: z.$ZodType) { const schema = _schema as z.$ZodTypes; const def = schema._zod.def; switch (def.type) { case "string": { // ... break; } case "object": { // ... break; } } } ``` -------------------------------- ### Define a catchall schema (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of using `z.catchall()` to validate unrecognized keys with a specific schema in Zod Mini. ```ts const DogWithStrings = z.catchall( z.object({ name: z.string(), age: z.number().optional(), }), z.string() ); DogWithStrings.parse({ name: "Yeller", extraKey: "extraValue" }); // ✅ DogWithStrings.parse({ name: "Yeller", extraKey: 42 }); // ❌ ``` -------------------------------- ### Demonstrate TypeScript Structural Typing Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/home.md This example illustrates TypeScript's structural typing, where types with identical structures are considered compatible, even if nominally different. ```ts type Cat = { name: string }; type Dog = { name: string }; const petCat = (cat: Cat) => {}; const fido: Dog = { name: "fido" }; petCat(fido); // works fine ``` -------------------------------- ### Define a catchall schema (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of using `.catchall()` to validate unrecognized keys with a specific schema in Zod. ```ts const DogWithStrings = z .object({ name: z.string(), age: z.number().optional(), }) .catchall(z.string()); DogWithStrings.parse({ name: "Yeller", extraKey: "extraValue" }); // ✅ DogWithStrings.parse({ name: "Yeller", extraKey: 42 }); // ❌ ``` -------------------------------- ### Registering, looking up, and removing schemas Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Shows how to add, check for, get, remove, and clear schemas in a registry. ```ts const mySchema = z.string(); myRegistry.add(mySchema, { description: "A cool schema!"}); myRegistry.has(mySchema); // => true myRegistry.get(mySchema); // => { description: "A cool schema!" } myRegistry.remove(mySchema); myRegistry.clear(); // wipe registry ``` -------------------------------- ### Make a schema nullish (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of making a schema nullish (optional and nullable) using Zod. ```ts const nullishYoda = z.nullish(z.literal("yoda")); ``` -------------------------------- ### Old transformer syntax (not available) Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/MIGRATION.md Examples of the old transformer syntax that is no longer available in Zod 3. ```typescript # not available z.transformer(A, B, func); A.transform(B, func) ``` -------------------------------- ### Regular Zod Check Methods Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of how common checks are performed in regular Zod using dedicated methods. ```ts import * as z from "zod"; z.string() .min(5) .max(10) .refine(val => val.includes("@")) .trim() ``` -------------------------------- ### Widen peer dependency for Zod 3 and Zod 4 Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of `package.json` showing how to widen the `peerDependencies` to support both Zod 3 (from `3.25.0`) and Zod 4. ```json // package.json { // ... "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } } ``` -------------------------------- ### Set Constraints (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of applying size constraints to a Zod set schema using Zod Mini's `check` method. ```ts z.set(z.string()).check(z.minSize(5)); // must contain 5 or more items z.set(z.string()).check(z.maxSize(5)); // must contain 5 or fewer items z.set(z.string()).check(z.size(5)); // must contain 5 items exactly ``` -------------------------------- ### Library code for Zod and Zod Mini compatibility Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of library code importing from `zod/v4/core` to ensure compatibility with both Zod and Zod Mini. ```ts // library code import * as z4 from "zod/v4/core"; export function acceptObjectSchema(schema: T){ // parse data z4.parse(schema, { /* somedata */}); // inspect internals schema._zod.def.shape; } ``` -------------------------------- ### Enable TypeScript Strict Mode Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/index.mdx Configuration snippet for `tsconfig.json` to enable TypeScript's strict mode, which is a best practice and required for Zod. ```ts // tsconfig.json { // ... "compilerOptions": { // ... "strict": true } } ``` -------------------------------- ### Set Constraints (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of applying size constraints to a Zod set schema using Zod's built-in methods. ```ts z.set(z.string()).min(5); // must contain 5 or more items z.set(z.string()).max(5); // must contain 5 or fewer items z.set(z.string()).size(5); // must contain 5 items exactly ``` -------------------------------- ### Circularity error example Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx An example of a recursive type inference error when defining a circular schema without a type annotation. ```ts const Activity = z.object({ name: z.string(), get subactivities() { // ^ ❌ 'subactivities' implicitly has return type 'any' because it does not // have a return type annotation and is referenced directly or indirectly // in one of its return expressions.ts(7023) return z.nullable(z.array(Activity)); } }); ``` -------------------------------- ### Object Schema Parse Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Example of parsing an object schema with Zod Mini to demonstrate bundle size for more complex types. ```ts const schema = z.object({ a: z.string(), b: z.number(), c: z.boolean() }); schema.parse({ a: "asdf", b: 123, c: true }); ``` -------------------------------- ### TypeScript Discriminated Union Type Example Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx A TypeScript example demonstrating how discriminated unions enable type narrowing based on a shared key. ```ts type MyResult = | { status: "success"; data: string } | { status: "failed"; error: string }; function handleResult(result: MyResult){ if(result.status === "success"){ result.data; // string } else { result.error; // string } } ``` -------------------------------- ### Locale error map customization (precedence example) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/error-customization.mdx Example of a locale error map set via z.config() for demonstrating error precedence. ```ts z.config(z.locales.en()); ``` -------------------------------- ### Basic Zod Schema Definition and Validation Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/index.mdx This example demonstrates how to define a basic Zod object schema, parse untrusted input data, and access the type-safe result. ```ts import * as z from "zod"; const User = z.object({ name: z.string(), }); // some untrusted data... const input = { /* stuff */ }; // the parsed result is validated and type safe! const data = User.parse(input); // so you can use it with confidence :) console.log(data.name); ``` -------------------------------- ### Define an object with optional properties (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of making object properties optional using Zod Mini. ```ts const Dog = z.object({ name: z.string(), age: z.optional(z.number()) }); Dog.parse({ name: "Yeller" }); // ✅ ``` -------------------------------- ### Global error map customization (precedence example) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/error-customization.mdx Example of a global error map set via z.config() for demonstrating error precedence. ```ts z.config({ customError: (iss) => "My custom error" }); ``` -------------------------------- ### Using .register() method Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Shows how to use the .register() method on a schema to add it to a registry. ```ts const mySchema = z.string(); mySchema.register(myRegistry, { description: "A cool schema!" }); // => mySchema ``` -------------------------------- ### Differentiating Zod 3 and Zod 4 schemas at runtime Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Code example showing how to check for the `_zod` property to determine if a schema is Zod 3 or Zod 4. ```ts import type * as z3 from "zod/v3"; import type * as z4 from "zod/v4/core"; declare const schema: z3.ZodTypeAny | z4.$ZodType; if ("_zod" in schema) { schema._zod.def; // Zod 4 schema } else { schema._def; // Zod 3 schema } ``` -------------------------------- ### User code demonstrating Zod and Zod Mini usage Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of user code calling a library function with schemas from both Zod and Zod Mini, showing simultaneous support. ```ts // user code import { acceptObjectSchema } from "your-library"; // Zod 4 import * as z from "zod"; acceptObjectSchema(z.object({ name: z.string() })); // Zod 4 Mini import * as zm from "zod/mini"; acceptObjectSchema(zm.object({ name: zm.string() })) ``` -------------------------------- ### Define never type Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of defining a 'never' type in Zod. ```ts z.never(); // inferred type: `never` ``` -------------------------------- ### Constraining the inferred output type of the input schema Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Example of how to constrain the inferred output type of the input schema, ensuring type compatibility. ```ts import * as z4 from "zod/v4/core"; // only accepts string schemas function inferSchema>(schema: T) { return schema; } inferSchema(z.string()); // ✅ inferSchema(z.number()); // ❌ The types of '_zod.output' are incompatible between these types. // // Type 'number' is not assignable to type 'string' ``` -------------------------------- ### Define unknown and any types Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of defining 'any' and 'unknown' types in Zod. ```ts // allows any values z.any(); // inferred type: `any` z.unknown(); // inferred type: `unknown` ``` -------------------------------- ### Import Zod Mini Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx How to import Zod Mini. ```ts import * as z from "zod/mini"; ``` -------------------------------- ### Importing Zod 3 and Zod 4 side-by-side Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Demonstrates how to import Zod 3 and Zod 4 from their respective subpaths to use them together in a library. ```ts import * as z3 from "zod/v3"; import * as z4 from "zod/v4/core"; type Schema = z3.ZodTypeAny | z4.$ZodType; function acceptUserSchema(schema: z3.ZodTypeAny | z4.$ZodType) { // ... } ``` -------------------------------- ### Development Commands Source: https://github.com/colinhacks/zod/blob/main/CLAUDE.md Key commands for project development using pnpm workspaces. ```bash pnpm build pnpm vitest run pnpm vitest run pnpm vitest run -t "" pnpm vitest run --update pnpm vitest run --update pnpm test:watch pnpm vitest run --coverage pnpm dev pnpm dev pnpm dev:play pnpm lint pnpm format pnpm fix ``` -------------------------------- ### Asynchronous transforms Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of defining and using an asynchronous transform to fetch data from a database. ```typescript const idToUser = z .string() .transform(async (id) => { // fetch user from database return db.getUserById(id); }); const user = await idToUser.parseAsync("abc123"); ``` ```typescript const idToUser = z.pipe( z.string(), z.transform(async (id) => { // fetch user from database return db.getUserById(id); })); const user = await idToUser.parse("abc123"); ``` -------------------------------- ### .describe() method (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Demonstrates using `z.describe()` and its equivalence to `z.meta()` for registering a schema description in Zod Mini. ```ts const emailSchema = z.email().check(z.describe("An email address")); // equivalent to z.email().check(z.meta({ description: "An email address" })); ``` -------------------------------- ### Parsing data with Zod Core functions Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/library-authors.mdx Demonstrates how to parse data using the top-level `z4.parse` function from Zod Core, as subclass methods are not available. ```ts function parseData(data: unknown, schema: T): z4.output { return z.parse(schema, data); } parseData("sup", z.string()); // => string ``` -------------------------------- ### .describe() method (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Demonstrates using `.describe()` and its equivalence to `.meta()` for registering a schema description in Zod. ```ts const emailSchema = z.email(); emailSchema.describe("An email address"); // equivalent to emailSchema.meta({ description: "An email address" }); ``` -------------------------------- ### Object schemas Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/json-schema.mdx Example of `z.object()` schema conversion in 'input' mode, where `additionalProperties` is not set. ```ts import * as z from "zod"; const schema = z.object({ name: z.string(), age: z.number() }); z.toJSONSchema(schema, { io: "input" }); // => { // type: 'object', // properties: { name: { type: 'string' }, age: { type: 'number' } }, // required: [ 'name', 'age' ], // } ``` -------------------------------- ### GUID Validation Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Validating any UUID-like identifier that does not strictly adhere to RFC 9562/4122 constraints. ```typescript z.guid(); ``` -------------------------------- ### Production Build Source: https://github.com/colinhacks/zod/blob/main/CONTRIBUTING.md Commands to build Zod documentation for production, requiring a GITHUB_TOKEN. ```sh export GITHUB_TOKEN=your_token_here # persists in shell session pnpm run --filter=@zod/docs build ``` -------------------------------- ### Password confirmation with 'when' (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates using the 'when' parameter to ensure the password confirmation refinement runs only if 'password' and 'confirmPassword' fields have no issues, regardless of other field errors in Zod Mini. ```ts const schema = z .object({ password: z.string().min(8), confirmPassword: z.string(), anotherField: z.string(), }) .check(z.refine((data) => data.password === data.confirmPassword, { message: "Passwords do not match", path: ["confirmPassword"], when(payload) { // no issues with `password` or `confirmPassword` return payload.issues.every((iss) => { const firstPathEl = iss.path?.[0]; return firstPathEl !== "password" && firstPathEl !== "confirmPassword"; }); }, })); schema.parse({ password: "asdf", confirmPassword: "asdf", anotherField: 1234 // ❌ this error will prevent the password check from running }); ``` -------------------------------- ### z.prettifyError() usage Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/error-formatting.mdx Shows how to use z.prettifyError() to get a human-readable string representation of the error. ```ts const pretty = z.prettifyError(result.error); ``` -------------------------------- ### Define a loose object schema Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of using `z.looseObject` to allow unknown keys to pass through. ```ts const LooseDog = z.looseObject({ name: z.string(), }); LooseDog.parse({ name: "Yeller", extraKey: true }); // => { name: "Yeller", extraKey: true } ``` -------------------------------- ### Prefault vs Default with mutating refinements Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Compares the behavior of prefault and default when a schema includes mutating refinements like trim and toUpperCase, showing how prefault values are processed through the schema. ```ts const a = z.string().trim().toUpperCase().prefault(" tuna "); a.parse(undefined); // => "TUNA" const b = z.string().trim().toUpperCase().default(" tuna "); b.parse(undefined); // => " tuna " ``` -------------------------------- ### Custom format error output Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of the error produced by a custom string format validation. ```ts myFormat.parse("invalid input!"); // ZodError: [ // { // "code": "invalid_format", // "format": "cool-id", // "path": [], // "message": "Invalid cool-id" // } // ] ``` -------------------------------- ### Creating a simple registry Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Demonstrates how to create a Zod registry with a specific metadata type. ```ts import * as z from "zod"; const myRegistry = z.registry<{ description: string }>(); ``` -------------------------------- ### ISO time validation - no offsets Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of invalid ISO time strings due to offsets. ```ts time.parse("03:15:00Z"); // ❌ (no `Z` allowed) time.parse("03:15:00+02:00"); // ❌ (no offsets allowed) ``` -------------------------------- ### Per-parse error customization Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/error-customization.mdx Example of passing a custom error map directly into the .parse() method. ```ts z.string().parse(12, { error: (iss) => "My custom error" }); ``` -------------------------------- ### Discriminating Zod Checks Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/core.mdx Example of using a switch statement on ._zod.def.check to discriminate between different $ZodChecks. ```ts const check = {} as z.$ZodChecks; const def = check._zod.def; switch (def.check) { case "less_than": case "greater_than": // ... break; } ``` -------------------------------- ### Common String Validations Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of common string validation methods in Zod and Zod Mini. ```typescript z.string().max(5); z.string().min(5); z.string().length(5); z.string().regex(/^[a-z]+$/); z.string().startsWith("aaa"); z.string().endsWith("zzz"); z.string().includes("---"); z.string().uppercase(); z.string().lowercase(); ``` ```typescript z.string().check(z.maxLength(5)); z.string().check(z.minLength(5)); z.string().check(z.length(5)); z.string().check(z.regex(/^[a-z]+$/)); z.string().check(z.startsWith("aaa")); z.string().check(z.endsWith("zzz")); z.string().check(z.includes("---")); z.string().check(z.uppercase()); z.string().check(z.lowercase()); ``` -------------------------------- ### Password confirmation with 'when' (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates using the 'when' parameter to ensure the password confirmation refinement runs only if 'password' and 'confirmPassword' fields are valid, regardless of other field errors. ```ts const baseSchema = z.object({ password: z.string().min(8), confirmPassword: z.string(), anotherField: z.string(), }); const schema = baseSchema .refine((data) => data.password === data.confirmPassword, { message: "Passwords do not match", path: ["confirmPassword"], // run if password & confirmPassword are valid when(payload) { return baseSchema .pick({ password: true, confirmPassword: true }) .safeParse(payload.value).success; }, }); schema.parse({ password: "asdf", confirmPassword: "asdf", anotherField: 1234 // ❌ this error will not prevent the password check from running }); ``` -------------------------------- ### Async Codec Definition Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/codecs.mdx Example of defining an asynchronous codec with `decode` and `encode` functions that return Promises. ```ts const asyncCodec = z.codec(z.string(), z.number(), { decode: async (str) => Number(str), encode: async (num) => num.toString() }); ``` -------------------------------- ### Using .apply() with Zod Mini Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates how to use `.apply()` with Zod Mini to incorporate an external function (`setCommonNumberChecks`) into a schema chain. ```ts function setCommonNumberChecks(schema: T) { return schema.check( z.minimum(0), z.maximum(100) ); } const schema = z.nullable( z.number().apply(setCommonNumberChecks) ); z.parse(schema, 0); // => 0 z.parse(schema, -1); // ❌ throws z.parse(schema, 101); // ❌ throws z.parse(schema, null); // => null ``` -------------------------------- ### Inverting a Codec Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/codecs.mdx Example of using `z.invertCodec()` to create a codec that reverses the input and output schemas and transformations. ```typescript const dateToString = z.invertCodec(stringToDate); dateToString.decode(new Date("2024-01-15T10:30:00.000Z")); // => string dateToString.encode("2024-01-15T10:30:00.000Z"); // => Date ``` ```typescript const dateToString = z.invertCodec(stringToDate); z.decode(dateToString, new Date("2024-01-15T10:30:00.000Z")); // => string z.encode(dateToString, "2024-01-15T10:30:00.000Z"); // => Date ``` -------------------------------- ### Commands Source: https://github.com/colinhacks/zod/blob/main/CONTRIBUTING.md Various `pnpm` commands for development and testing. ```sh pnpm build ``` ```sh pnpm test ``` ```sh pnpm test:watch ``` ```sh pnpm test ``` ```sh pnpm test --filter ``` ```sh pnpm dev:play ``` -------------------------------- ### Defining a Codec Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/codecs.mdx Example of defining a codec to transform an ISO date string to a Date object and vice-versa. ```typescript const stringToDate = z.codec( z.iso.datetime(), // input schema: ISO date string z.date(), // output schema: Date object { decode: (isoString) => new Date(isoString), // ISO string → Date encode: (date) => date.toISOString(), // Date → ISO string } ); ``` -------------------------------- ### Regular Zod vs. Zod Mini Chained Methods Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/packages/mini.mdx Comparison of method chaining in regular Zod versus functional checks in Zod Mini. ```ts // regular Zod z.string().min(5).max(10).trim() // Zod Mini z.string().check(z.minLength(5), z.maxLength(10), z.trim()); ``` -------------------------------- ### z.flattenError() usage Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/error-formatting.mdx Shows how to use z.flattenError() to get a shallow error object with formErrors and fieldErrors. ```ts const flattened = z.flattenError(result.error); // { errors: string[], properties: { [key: string]: string[] } } { formErrors: [ 'Unrecognized key: "extraKey"' ], fieldErrors: { username: [ 'Invalid input: expected string, received number' ], favoriteNumbers: [ 'Invalid input: expected number, received string' ] } } ``` -------------------------------- ### Handling errors with .safeParse() Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/basics.mdx Using .safeParse() to get a result object instead of throwing an error. ```ts const result = Player.safeParse({ username: 42, xp: "100" }); if (!result.success) { result.error; // ZodError instance } else { result.data; // { username: string; xp: number } } ``` -------------------------------- ### Using .meta() to register metadata (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/metadata.mdx Conveniently registers metadata in z.globalRegistry using the .meta() method in Zod Mini. ```ts const emailSchema = z.email().check( z.meta({ id: "email_address", title: "Email address", description: "Please enter a valid email address", }) ); ``` -------------------------------- ### Define a strict object schema Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of using `z.strictObject` to throw an error when unknown keys are found. ```ts const StrictDog = z.strictObject({ name: z.string(), }); StrictDog.parse({ name: "Yeller", extraKey: true }); // ❌ throws ``` -------------------------------- ### Define an object with optional properties (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of making object properties optional using Zod. ```ts const Dog = z.object({ name: z.string(), age: z.number().optional(), }); Dog.parse({ name: "Yeller" }); // ✅ ``` -------------------------------- ### Configure Docsify Site Settings Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/index.html This snippet defines the `window.$docsify` object, which configures various aspects of the Docsify documentation site, such as the homepage, navigation levels, repository link, router mode, and lists of external links. ```javascript window.$docsify = { // Vercel no longer serves root-level README.md from static deployments. homepage: "home.md", subMaxLevel: 1, maxLevel: 3, auto2top: true, repo: "colinhacks/zod", routerMode: "history", crossOriginLinks: [ "https://github.com/colinhacks/zod/actions?query=branch%3Amain", "https://opensource.org/licenses/MIT", "https://www.npmjs.com/package/zod", "https://discord.gg/KaSRdyX2vc", "https://discord.gg/RcG33DQJdf", "https://github.com/colinhacks/zod/issues/new", "https://twitter.com/colinhacks", "https://trpc.io/", "https://zod.dev/", "https://deno.land/x/zod", "https://zod.dev/blog/clerk-fellowship", "https://go.clerk.com/hqN4rp7", "https://go.clerk.com/Qgor5NQ", "https://go.clerk.com/PKHrcwh" ], noCompileLinks: [ "https://github.com/colinhacks/zod/actions?query=branch%3Amain", "https://opensource.org/licenses/MIT", "https://www.npmjs.com/package/zod", "https://discord.gg/KaSRdyX2vc", "https://discord.gg/RcG33DQJdf", "https://github.com/colinhacks/zod/issues/new", "https://twitter.com/colinhacks", "https://trpc.io/", "https://zod.dev/", "https://deno.land/x/zod", "https://zod.dev/blog/clerk-fellowship", "https://go.clerk.com/hqN4rp7", "https://go.clerk.com/Qgor5NQ", "https://go.clerk.com/PKHrcwh" ] }; ``` -------------------------------- ### Using .superRefine() (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates how to use .superRefine() to add multiple custom issues with different error codes and messages based on validation logic. ```ts const UniqueStringArray = z.array(z.string()).superRefine((val, ctx) => { if (val.length > 3) { ctx.addIssue({ code: "too_big", maximum: 3, origin: "array", inclusive: true, message: "Too many items 😡", input: val, }); } if (val.length !== new Set(val).size) { ctx.addIssue({ code: "custom", message: `No duplicates allowed.`, input: val, }); } }); ``` -------------------------------- ### Extract inner schema from ZodNullable (Zod) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of extracting the inner schema from a ZodNullable instance in Zod. ```ts nullableYoda.unwrap(); // ZodLiteral<"yoda"> ``` -------------------------------- ### Using Zod's Exported Email Regexes Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples demonstrating the use of predefined email regular expressions provided by Zod, including HTML5 and RFC 5322 patterns. ```typescript // Zod's default email regex z.email(); z.email({ pattern: z.regexes.email }); // equivalent // the regex used by browsers to validate input[type=email] fields // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email z.email({ pattern: z.regexes.html5Email }); // the classic emailregex.com regex (RFC 5322) z.email({ pattern: z.regexes.rfc5322Email }); // a loose regex that allows Unicode (good for intl emails) z.email({ pattern: z.regexes.unicodeEmail }); ``` -------------------------------- ### Using a Codec for Decoding and Encoding Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/codecs.mdx Demonstrates how `decode` and `encode` behave differently when using a codec that diverges input and output types. ```typescript stringToDate.decode("2024-01-15T10:30:00.000Z") // => Date stringToDate.encode(new Date("2024-01-15T10:30:00.000Z")) // => string ``` ```typescript z.decode(stringToDate, "2024-01-15T10:30:00.000Z") // => Date z.encode(stringToDate, new Date("2024-01-15T10:30:00.000Z")) // => string ``` -------------------------------- ### Enum with String TypeScript Enum Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Example of using `z.enum` with an externally declared TypeScript string enum. ```ts enum Fish { Salmon = "Salmon", Tuna = "Tuna", Trout = "Trout", } const FishEnum = z.enum(Fish); ``` -------------------------------- ### Making a Schema Optional (Zod Mini) Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Demonstrates how to make a schema optional using `z.optional()` in Zod Mini. ```ts z.optional(z.literal("yoda")); ``` -------------------------------- ### Setting a default value with a function Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Shows how to provide a function to generate a default value dynamically whenever a default value is needed. ```ts const randomDefault = z.number().default(Math.random); randomDefault.parse(undefined); // => 0.4413456736055323 randomDefault.parse(undefined); // => 0.1871840107401901 randomDefault.parse(undefined); // => 0.7223408162401552 ``` ```ts const randomDefault = z._default(z.number(), Math.random); z.parse(randomDefault, undefined); // => 0.4413456736055323 z.parse(randomDefault, undefined); // => 0.1871840107401901 z.parse(randomDefault, undefined); // => 0.7223408162401552 ``` -------------------------------- ### Handling cycles with $ref Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/json-schema.mdx Example of a self-referencing schema and how toJSONSchema represents cycles using $ref by default. ```ts const User = z.object({ name: z.string(), get friend() { return User; } }); z.toJSONSchema(User); // => { // type: 'object', // properties: { name: { type: 'string' }, friend: { '$ref': '#' } }, // required: [ 'name', 'friend' ], // additionalProperties: false, // } ``` -------------------------------- ### Unrepresentable Zod Types Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/json-schema.mdx Examples of Zod types that do not have a direct JSON Schema analog and cannot be reasonably represented. ```ts z.bigint(); // ❌ z.int64(); // ❌ z.symbol(); // ❌ z.undefined(); // ❌ z.void(); // ❌ z.date(); // ❌ z.map(); // ❌ z.set(); // ❌ z.transform(); // ❌ z.nan(); // ❌ z.custom(); // ❌ ``` -------------------------------- ### Array-specific validations Source: https://github.com/colinhacks/zod/blob/main/packages/docs/content/api.mdx Examples of array-specific validations like min, max, and length using Zod and Zod Mini. ```ts z.array(z.string()).min(5); // must contain 5 or more items z.array(z.string()).max(5); // must contain 5 or fewer items z.array(z.string()).length(5); // must contain 5 items exactly ``` ```ts z.array(z.string()).check(z.minLength(5)); // must contain 5 or more items z.array(z.string()).check(z.maxLength(5)); // must contain 5 or fewer items z.array(z.string()).check(z.length(5)); // must contain 5 items exactly ``` -------------------------------- ### Implement Dark Theme Toggling with System Preference Source: https://github.com/colinhacks/zod/blob/main/packages/docs-v3/index.html This JavaScript code provides functions to check and toggle the dark theme based on the user's system preferences. It applies the 'dark' class to the body and sets a 'data-theme' attribute on the document's root element. ```javascript localStorage.removeItem("dark-theme"); function checkDark() { return ( // localStorage.getItem("dark-theme") === "true" ?? window.matchMedia("(prefers-color-scheme: dark)").matches ?? false ); } let isDark = checkDark(); toggleDarkTheme(isDark); window .matchMedia("(prefers-color-scheme: dark)") .addEventListener("change", (e) => toggleDarkTheme(e.matches())); // document.querySelector(".theme-btn").addEventListener("click", () => { // const isDark = checkDark(); // console.log("isDark", isDark); // toggleDarkTheme(!isDark); // }); function toggleDarkTheme(isDark) { if (isDark) { document.body.classList.add("dark"); } else { document.body.classList.remove("dark"); } document.documentElement.setAttribute( "data-theme", isDark ? "dark" : "light" ); // localStorage.setItem("dark-theme", isDark ? "true" : "false"); } ```