### Zod Benchmark Example Source: https://zod.dev/v4 This code snippet demonstrates how to run Zod benchmarks. It includes setup for different Zod versions and various validation scenarios. ```typescript import { performance } from "perf_hooks"; import zod from "zod"; const schemas = { "zod v3": { schema: zod.object({ name: zod.string() }) }, "zod v4": { schema: zod.object({ name: zod.string() }) }, }; const data = { name: "test" }; const results = {}; for (const [name, { schema }] of Object.entries(schemas)) { const start = performance.now(); for (let i = 0; i < 100000; i++) { schema.parse(data); } const end = performance.now(); results[name] = end - start; } console.log(results); ``` -------------------------------- ### Basic Zod 4 Mini Example Source: https://zod.dev/library-authors A minimal example demonstrating the import and usage of Zod 4 Mini. ```typescript import { z } from "zod"; // Zod 4 Mini ``` -------------------------------- ### Add string metadata with examples Source: https://zod.dev/metadata Demonstrates adding metadata to a Zod string schema, including example values. ```typescript myRegistry.add(z.string(), { examples: ["hello", "world"] }); ``` -------------------------------- ### Install Zod Dependencies Source: https://zod.dev/v4 Command to install project dependencies using pnpm after cloning the Zod repository. ```bash pnpm install ``` -------------------------------- ### Zod Mini Bundle Size Example Source: https://zod.dev/v4 A minimal Zod Mini example demonstrating its reduced bundle size. ```typescript import * as z from "zod/mini"; const schema = z.boolean(); schema.parse(false); ``` -------------------------------- ### Zod Preprocess Schema Example Source: https://zod.dev/packages/core Example of using ZodPreprocess for data transformation before validation. ```typescript new ZodPreprocess() ``` -------------------------------- ### Add number metadata with examples Source: https://zod.dev/metadata Shows how to attach metadata to a Zod number schema, providing example numerical values. ```typescript myRegistry.add(z.number(), { examples: [1, 2, 3] }); ``` -------------------------------- ### Install Zod via npm Source: https://zod.dev/ Install the Zod package using npm for use in Node.js projects. ```bash npm install zod ``` -------------------------------- ### Zod Mini Example Source: https://zod.dev/error-customization Demonstrates basic usage of Zod Mini with a string schema and safeParse. ```typescript import * as z from "zod/mini"; const result = z.string().safeParse("hello"); console.log(result); ``` -------------------------------- ### Zod File Schema Example Source: https://zod.dev/packages/core Example of using ZodFile for validating file inputs. ```typescript new ZodFile() ``` -------------------------------- ### Tuple Parsing Example Source: https://zod.dev/v4/changelog Demonstrates how to define a tuple with specific types and an optional rest element. This example shows a tuple that must contain a string, followed by any number of strings. ```typescript z.tuple([z.string(), ...z.string()]) ``` -------------------------------- ### Register a Schema Source: https://zod.dev/metadata This example demonstrates how to register a schema with a registry. It assumes `myRegistry` is an existing Zod registry instance. ```typescript myRegistry.register(mySchema); ``` -------------------------------- ### Run Zod Benchmarks Source: https://zod.dev/v4 Instructions to clone the Zod repository, switch to the v4 branch, install dependencies, and run specific benchmarks. ```sh $ git clone git@github.com:colinhacks/zod.git $ cd zod $ git switch v4 $ pnpm install ``` ```sh $ pnpm bench ``` -------------------------------- ### Importing Zod Source: https://zod.dev/packages/zod Import the Zod library to start defining schemas. This is a common starting point for using Zod in your project. ```typescript import * as z from "zod" ``` -------------------------------- ### Formatted Error String Example Source: https://zod.dev/error-formatting This is an example of the string returned by `z.prettifyError()`. ```text Invalid input: expected number, received string ``` -------------------------------- ### Zod Codec Schema Example Source: https://zod.dev/packages/core Shows the ZodCodec schema, likely for encoding/decoding data. ```typescript new ZodCodec() ``` -------------------------------- ### Zod Optional Schema Example Source: https://zod.dev/packages/core Illustrates creating an optional schema with ZodOptional. ```typescript new ZodOptional() ``` -------------------------------- ### Zod String Schema Examples Source: https://zod.dev/v4 Demonstrates basic string schema validation with Zod, including length constraints. ```typescript z.string().min(5).max(10) ``` -------------------------------- ### String Encoding Example Source: https://zod.dev/codecs Demonstrates encoding a string using `uriComponent.encode`. This is useful for preparing strings for use in URIs. ```typescript uriComponent.encode("Hello World!"); // => "Hello%20World!" ``` -------------------------------- ### JSON Schema Output Example Source: https://zod.dev/json-schema This is an example of the JSON schema output generated by `User.toJSONSchema()`. It represents the structure and types defined in the Zod schema. ```json { "type": "object", "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" } }, "required": [ "firstName", "lastName" ], "additionalProperties": false } ``` -------------------------------- ### Zod Transform Schema Example Source: https://zod.dev/packages/core Demonstrates how to use ZodTransform to modify parsed data. ```typescript new ZodTransform() ``` -------------------------------- ### Example of z.prettifyError() Output Source: https://zod.dev/error-formatting Demonstrates the string output generated by `z.prettifyError()` for a given error object. ```javascript const result = await schema.safeParseAsync(data); if (!result.success) { console.error(z.prettifyError(result.error)); } ``` -------------------------------- ### Zod Pre-fault Schema Example Source: https://zod.dev/packages/core Demonstrates the use of ZodPre-fault for pre-validation logic. ```typescript new ZodPrefault() ``` -------------------------------- ### Zod Function Implementation Example Source: https://zod.dev/v4/changelog Illustrates how to implement a Zod schema for a function. This is useful for validating function arguments and return types. ```typescript myFunction.implement({ name: z.string() }); ``` -------------------------------- ### Parsing Data with Zod Source: https://zod.dev/library-authors Demonstrates how to parse data using a Zod schema. Includes an example of inspecting schema internals. ```typescript parse(schema, { /* somedata */ }); }); // inspect internals ``` -------------------------------- ### Basic String Schema Source: https://zod.dev/library-authors Example of defining a Zod schema for a string. ```typescript import { z } from "zod"; const schema = z.string(); // Output: string ``` -------------------------------- ### Creating a BigInt Schema with Zod Mini Source: https://zod.dev/packages/mini Define a schema for a BigInt using z.bigint. This example creates a schema that validates BigInt values. ```javascript const bigIntValue = z.bigint(); ``` -------------------------------- ### Install Zod 4 Source: https://zod.dev/v4/versioning Install Zod version 4 or later using npm. This command ensures you get the latest stable version of Zod 4. ```bash npm install zod@^4.0.0 ``` -------------------------------- ### Creating a URL Schema with Zod Mini Source: https://zod.dev/packages/mini Define a schema for a URL using z. தருக. This example creates a schema that validates URL strings. ```javascript const urlSchema = z. தருக(); ``` -------------------------------- ### Zod Pipe Schema Example Source: https://zod.dev/packages/core Illustrates the use of ZodPipe for chaining validation and transformation steps. ```typescript new ZodPipe() ``` -------------------------------- ### Zod Success Schema Example Source: https://zod.dev/packages/core Shows the ZodSuccess schema, likely for handling successful validation outcomes. ```typescript new ZodSuccess() ``` -------------------------------- ### Zod Set Schema Example Source: https://zod.dev/packages/core Demonstrates the usage of the ZodSet schema type for validating sets. ```typescript new ZodSet() ``` -------------------------------- ### Example of Treeified Zod Error Output Source: https://zod.dev/error-formatting This example shows the structure of the nested object produced by `z.treeifyError()`. It includes examples of error messages for unrecognized keys, properties, and usernames. ```json { "errors": [ "Unrecognized key: \"extraKey\"" ], "properties": {}, "username": {} } ``` -------------------------------- ### Creating a Symbol Schema with Zod Mini Source: https://zod.dev/packages/mini Define a schema for a Symbol using z.symbol. This example creates a schema that validates Symbol values. ```javascript const symbolValue = z.symbol(); ``` -------------------------------- ### Zod Object Validation Example Source: https://zod.dev/packages/core Example of validating an object type in Zod. ```typescript case "object": { } ``` -------------------------------- ### Zod String Validation Example Source: https://zod.dev/packages/core Example of validating a string type in Zod. ```typescript case "string": { } ``` -------------------------------- ### Zod Mini: Functional API Examples Source: https://zod.dev/v4 Demonstrates the functional API of Zod Mini, using wrapper functions for common schema operations like optional, union, and extend. ```javascript import * as z from "zod/mini"; z.optional(z.string()); z.union([z.string(), z.number()]); z.extend(z.object({ /* ... */ }), { age: z.number() }); ``` -------------------------------- ### Importing Zod v3 and v4 Source: https://zod.dev/library-authors Demonstrates how to import Zod v3 and v4 for use in your library. Ensure you have the correct versions installed. ```typescript import type * as z3 from "zod/v3"; import type * as z4 from "zod/v4/core"; ``` ```typescript declare const schema: z3.ZodTypeAny | z4.ZodTypeAny; ``` -------------------------------- ### Zod Error Object Example Source: https://zod.dev/basics An example of a Zod error object structure. ```json { expected: 'string', code: 'invalid_type' } ``` -------------------------------- ### Running Zod Benchmarks Source: https://zod.dev/v4 Instructions to run the Zod benchmarking playground. Navigate to the 'packages/tsc' directory and execute the benchmark command. ```bash $ cd packages/tsc $ pnpm bench object-with-extend ``` -------------------------------- ### Zod Nullable Schema Example Source: https://zod.dev/packages/core Shows how to define a schema that accepts null values using ZodNullable. ```typescript new ZodNullable() ``` -------------------------------- ### Zod Catch Schema Example Source: https://zod.dev/packages/core Example of using ZodCatch to handle validation errors gracefully. ```typescript new ZodCatch() ``` -------------------------------- ### Zod Default Schema Example Source: https://zod.dev/packages/core Example of providing a default value for a schema property using ZodDefault. ```typescript new ZodDefault() ``` -------------------------------- ### Creating a Schema with Pipeline using Zod Mini Source: https://zod.dev/packages/mini Use z.pipeline to chain transformations and refinements. This example first transforms a string to uppercase and then refines it to be non-empty. ```javascript const processedString = z.string().pipeline( z.transform((s) => s.toUpperCase()), z.refine((s) => s.length > 0, 'String cannot be empty') ); ``` -------------------------------- ### Zod String Schema Examples Source: https://zod.dev/v4 Demonstrates various string validation methods available in Zod, such as email, base64, and JWT validation. ```typescript z.string().email(); ``` ```typescript z.string().base64(); ``` ```typescript z.string().base64url(); ``` ```typescript z.string().jwt(); ``` ```typescript z.string().lowercase(); ``` -------------------------------- ### Importing and Using Zod Mini Source: https://zod.dev/library-authors Shows how to import and use the 'zod/mini' module to define an object schema with string properties. ```typescript import { as zm } from "zod/mini"; acceptObjectSchema(zm.object({ name: zm.string() })) ``` -------------------------------- ### Creating a UUID Schema with Zod Mini Source: https://zod.dev/packages/mini Define a schema for a UUID using z.uuid. This example creates a schema that validates UUID strings. ```javascript const uuidSchema = z.uuid(); ``` -------------------------------- ### Adding Metadata via `.meta()` Method Source: https://zod.dev/v4 Shows how to use the `.meta()` method to conveniently add schemas to the global registry. ```typescript z.string().meta({ id: "email_address", title: "Email address", description: "Provide your email", examples: ["naomie@example.com"], // ... }); ``` -------------------------------- ### String Validation with superRefine Source: https://zod.dev/v4/changelog Demonstrates how to use superRefine with string validation in Zod. This example shows how to access context path and highlights a change in availability. ```typescript string().superRefine((val, ctx) => { ctx.path; // ❌ no longer available }); ``` -------------------------------- ### Example Usage of Library Function with Zod/Zod Mini Source: https://zod.dev/library-authors Demonstrates how user code can pass schemas from both Zod and Zod Mini to a library function that imports from 'zod/v4/core'. ```typescript // user code import { acceptObjectSchema } from \ ``` -------------------------------- ### Creating an Array Schema with Zod Mini Source: https://zod.dev/packages/mini Define a schema for an array of a specific type using z.array. This example creates a schema for an array of strings. ```javascript const stringArray = z.array(z.string()); ``` -------------------------------- ### Import Zod Mini Source: https://zod.dev/packages/mini Import the Zod Mini library. This is the standard way to begin using Zod Mini in your project. ```typescript import * as z from "zod/mini" ``` -------------------------------- ### Basic Schema Parsing with Zod Mini Source: https://zod.dev/packages/mini Demonstrates how to define a schema and parse data using Zod Mini. This is a fundamental example of Zod's parsing capabilities. ```typescript const schema = z.object({ a: z.string(), b: z.number(), c: z.boolean() }); schema.parse({ a: "asdf", b: 123, c: true, }); ``` -------------------------------- ### Example package.json for Zod Peer Dependency Source: https://zod.dev/library-authors This snippet shows how to configure peer dependencies in your package.json to include Zod. It specifies compatible versions for Zod 3 and Zod 4. ```json // package.json { // ... "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } } ``` -------------------------------- ### Zod Schemas for Primitive Types Source: https://zod.dev/json-schema Provides examples of defining schemas for basic primitive types like strings, numbers, booleans, and null. ```typescript import { z } from "zod"; z.string(); z.number(); z.boolean(); z.null(); z.undefined(); z.unknown(); z.any(); ``` -------------------------------- ### Define String Type with GUID Format Source: https://zod.dev/json-schema Define a string schema with the 'guid' format using Zod. This is an alias for the 'uuid' format. ```typescript z.guid(); // => { type: "string", format: "uuid" } ``` -------------------------------- ### String with Starts With Validation Source: https://zod.dev/v4/changelog Defines a Zod schema for a string that must start with a specific prefix. Useful for validating protocol identifiers or specific formatting. ```typescript import { z } from "zod"; const startsWithSchema = z.string().startsWith("http"); startsWithSchema.parse("https://example.com"); // succeeds // startsWithSchema.parse("ftp://example.com"); // throws ZodError ``` -------------------------------- ### Cloning a Schema with .clone(def) Source: https://zod.dev/packages/mini Illustrates how to create an identical clone of an existing schema using the `.clone(def)` method, optionally providing a new definition. ```typescript const mySchema = z.string() mySchema.clone(mySchema._zod.def); ``` -------------------------------- ### Zod Date Codec Example Source: https://zod.dev/codecs Demonstrates how to use the Zod date codec to parse an ISO string into a Date object. This is useful for handling date inputs. ```typescript zod.date(), // output schema: Date object decode: (isoString) => new Date(isoString), // ISO string → Date ``` -------------------------------- ### Get Input JSON Schema Source: https://zod.dev/json-schema Use the `io: "input"` option to get the input type of a schema, which is useful for schemas with transformations or pipes. ```typescript const mySchema = z.string().transform(val => val.length).pipe(z.number()); const jsonSchemaInput = z.toJSONSchema(mySchema, { io: "input" }); // => { type: "string" } ``` -------------------------------- ### Basic String Schema Usage Source: https://zod.dev/codecs Demonstrates the basic usage of a Zod string schema, where input and output types are identical. Shows parse, decode, and encode methods. ```typescript const schema = z.string(); type Input = z.input; // string type Output = z.output; // string schema.parse("asdf"); // => "asdf" schema.decode("asdf"); // => "asdf" schema.encode("asdf"); // => "asdf" ``` -------------------------------- ### Zod Mini API Introduction Source: https://zod.dev/v4 Explains that Zod Mini offers a functional, tree-shakable API that mirrors Zod's API but uses wrapper functions instead of methods. ```plaintext It's a Zod variant with a functional, tree-shakable API that corresponds one-to-one with zod. Where Zod uses methods, Zod Mini generally uses wrapper functions: ``` -------------------------------- ### Get Unix Epoch Seconds from Date Source: https://zod.dev/codecs Use `date.getTime()` to retrieve the number of milliseconds since the Unix epoch from a Date object. This can then be divided by 1000 to get seconds. ```typescript date.getTime(); ``` -------------------------------- ### Switching to Zod Mini from Zod Source: https://zod.dev/v4 Shows how to update your import statement to use Zod Mini instead of the standard Zod library. This change leverages the more functional API for better tree-shaking. ```bash import { z } from "zod/mini"; import { z } from "zod"; ``` -------------------------------- ### Adding Metadata to a Zod String Schema Source: https://zod.dev/v4 Use the .meta() method to add metadata to a Zod schema. This example shows how to add an id, title, description, and examples to a string schema. ```typescript z.string().meta({ id: "email_address", title: "Email address", description: "Provide your email", examples: ["test@example.com"] }) ``` -------------------------------- ### Error Formatting Example Source: https://zod.dev/error-formatting This example demonstrates how Zod formats errors for a simple schema with a single string input. The output shows the `_errors` array containing the specific validation message. ```typescript const schema = z.string(); schema.safeParse(123); /* { success: false, error: { _errors: [ "Invalid input: expected string, received number" ] } } */ ``` -------------------------------- ### Using zod/mini for Reduced Bundle Size Source: https://zod.dev/v4 Import 'zod/mini' instead of 'zod' to significantly reduce the core bundle size. This example demonstrates a simple boolean schema parsed with the mini version. ```typescript import * as z from "zod/mini"; const schema = z.boolean(); schema.parse(false); ``` -------------------------------- ### Augment GlobalMeta Interface with Declaration Merging Source: https://zod.dev/metadata Provides an example of augmenting the GlobalMeta interface in Zod using TypeScript's declaration merging to add custom metadata fields like 'examples'. ```typescript declare module "zod" { interface GlobalMeta { // add new fields here examples?: unknown[]; } } // forces TypeScript to consider the file a module export {} ``` -------------------------------- ### Using .describe() vs .meta() Source: https://zod.dev/metadata The .describe() method is a shorthand for registering a schema in z.globalRegistry with just a description field. .meta() is the recommended approach. ```typescript const emailSchema = z.email(); ``` -------------------------------- ### Custom Registry Referencing Inferred Types Source: https://zod.dev/metadata Creates a custom registry where metadata can include examples of the schema's inferred output type using z.$output. It then adds string and number schemas with their respective examples. ```typescript import * as z from "zod"; type MyMeta = { examples: z.$output[] }; const myRegistry = z.registry(); myRegistry.add(z.string(), { examples: ["hello", "world"] }); myRegistry.add(z.number(), { examples: [1, 2, 3] }); ``` -------------------------------- ### Add, Check, and Get Schemas from a Registry Source: https://zod.dev/metadata Demonstrates how to add a schema with associated metadata to a registry, check if a schema exists in the registry, and retrieve the metadata for a given schema. ```typescript const mySchema = z.string(); myRegistry.add(mySchema, { description: "A cool schema!"}); myRegistry.has(mySchema); // => true myRegistry.get(mySchema); // => { description: "A cool schema!" } ``` -------------------------------- ### Custom Error Map Example Source: https://zod.dev/error-customization This example demonstrates how to define a custom error map for a Zod schema to override default error messages. It shows how to handle specific error codes like 'too_small' and provide custom messages. ```typescript const z = require("zod"); const schema = z.object({ username: z.string().min(1, { message: "Username is required." }), password: z.string().min(8, { message: "Password must be at least 8 characters long." }), }); const result = schema.safeParse({ username: "", password: "12345", }); if (!result.success) { console.log(result.error.format()); } ``` -------------------------------- ### Development Setup for Peer Dependencies Source: https://zod.dev/library-authors When developing a library that has Zod as a peer dependency, also add 'zod' to your devDependencies to satisfy the peer dependency requirement during development. ```json { "peerDependencies": { "zod": "^4.0.0" }, "devDependencies": { "zod": "^4.0.0" } } ``` -------------------------------- ### Zod Readonly Schema Example Source: https://zod.dev/packages/core Demonstrates creating a read-only schema with ZodReadonly. ```typescript new ZodReadonly() ``` -------------------------------- ### Importing core utilities via namespace Source: https://zod.dev/v4/changelog Demonstrates accessing core utilities via the `z.core` namespace, as contents of `zod/v4/core` are re-exported from `zod` and `zod/mini`. ```typescript import * as z from "zod"; function handleError(iss: z.core.$ZodError) { // do stuff } ``` -------------------------------- ### Zod Custom Schema Example Source: https://zod.dev/packages/core Shows how to define custom validation logic with ZodCustom. ```typescript new ZodCustom() ``` -------------------------------- ### Zod NaN Schema Example Source: https://zod.dev/packages/core Demonstrates the ZodNaN schema for validating Not-a-Number values. ```typescript new ZodNaN() ``` -------------------------------- ### Using a Zod Codec for Decoding and Encoding Source: https://zod.dev/codecs Shows the practical application of the `stringToDate` codec, demonstrating how `decode` converts an ISO string to a Date object and `encode` converts a Date object back to an ISO string. ```typescript stringToDate.decode("2024-01-15T10:30:00.000Z") // => Date stringToDate.encode(new Date("2024-01-15T10:30:00.000Z")) // => string ``` -------------------------------- ### Zod .transform() Example Source: https://zod.dev/v4 Demonstrates the usage of the .transform() method, which can alter the inferred type of a schema. ```typescript const Squared = z.number().transform(val => val ** 2); // => ZodPipe ``` -------------------------------- ### String with Transform Source: https://zod.dev/v4/changelog Transforms a string value after validation. For example, converting a string to uppercase after validation. ```typescript import { z } from "zod"; const transformSchema = z.string().transform(val => val.toUpperCase()); transformSchema.parse("hello"); // returns "HELLO" ``` -------------------------------- ### Using .describe() and .meta() for Schema Metadata Source: https://zod.dev/metadata Demonstrates the usage of .describe() as a shorthand for .meta({ description: ... }) to add metadata to Zod schemas. .meta() is the recommended approach. ```typescript const emailSchema = z.email(); emailSchema.describe("An email address"); // equivalent to emailSchema.meta({ description: "An email address" }); ``` -------------------------------- ### Registering Schema with Custom Registry (Convenience Method) Source: https://zod.dev/v4 Illustrates using the `.register()` method for adding schemas to a custom registry. ```typescript emailSchema.register(myRegistry, { title: "Email address", description: "..." }) // => returns emailSchema ``` -------------------------------- ### Loose Object Schema Example Source: https://zod.dev/v4/changelog Defines a loose object schema, which is the default behavior for z.object(). ```typescript z.looseObject(); ``` -------------------------------- ### Creating a Schema with Catch-all Value using Zod Mini Source: https://zod.dev/packages/mini Use z.catchall to define a schema for unknown keys in an object. This example allows any additional string keys with number values. ```javascript const schemaWithCatchall = z.object({ name: z.string(), }).catchall(z.number()); ``` -------------------------------- ### Zod Template Literal Schema Example Source: https://zod.dev/packages/core Illustrates defining template literal types with ZodTemplateLiteral. ```typescript new ZodTemplateLiteral() ``` -------------------------------- ### Using Zod Mini for Schema Definition Source: https://zod.dev/v4 Demonstrates how to use Zod Mini's API for defining schemas, including custom checks and first-class checks like 'lt' and 'lte'. This version is optimized for tree-shaking. ```typescript z.refine(); // first-class checks z.lt(value); z.lte(value, // alias: z.maximum() z.gt(value); ``` -------------------------------- ### Zod Non-Optional Schema Example Source: https://zod.dev/packages/core Illustrates how to explicitly mark a schema as non-optional using ZodNonOptional. ```typescript new ZodNonOptional() ``` -------------------------------- ### String Codec Decode and Encode Source: https://zod.dev/codecs Demonstrates decoding and encoding with a string codec that includes error catching. Shows how to handle invalid inputs and expected outputs. ```typescript stringWithCatch.decode(123); // => "hello" stringWithCatch.encode(123); // => ZodError: Expected string, received number ``` -------------------------------- ### Zod Enum Schema Example Source: https://zod.dev/packages/core Illustrates how to define and use ZodEnum for validating enumerated values. ```typescript new ZodEnum() ``` -------------------------------- ### Register Schema Metadata using .meta() (Zod) Source: https://zod.dev/metadata Demonstrates using the .meta() method to register metadata for a schema in z.globalRegistry. This is a convenient alternative to .register(). ```typescript const emailSchema = z.email().meta({ id: "email_address", title: "Email address", description: "Please enter a valid email address", }); ``` -------------------------------- ### Inspecting Schema Internals Source: https://zod.dev/library-authors Example of accessing the definition object of a Zod schema to inspect its shape. ```typescript schema._zod.def.shape; ``` -------------------------------- ### Zod Mini: Top-Level Refinements Source: https://zod.dev/v4 Provides examples of various top-level refinements available in Zod Mini for custom checks, range constraints, size limits, and string formatting. ```javascript import * as z from "zod/mini"; // custom checks z.refine(); // first-class checks z.lt(value); z.lte(value); // alias: z.maximum() z.gt(value); z.gte(value); // alias: z.minimum() z.positive(); z.negative(); z.nonpositive(); z.nonnegative(); z.multipleOf(value); z.maxSize(value); z.minSize(value); z.size(value); z.maxLength(value); z.minLength(value); z.length(value); z.regex(regex); z.lowercase(); z.uppercase(); z.includes(value); z.startsWith(value); z.endsWith(value); z.property(key, schema); // for object schemas; check `input[key]` against `schema` z.mime(value); // for file schemas (see below) // overwrites (these *do not* change the inferred type!) z.overwrite(value => newValue); z.normalize(); z.trim(); z.toLowerCase(); z.toUpperCase(); ``` -------------------------------- ### String Starts With Check Source: https://zod.dev/packages/mini Use `z.startsWith(value)` to validate if a string begins with a specific prefix. ```typescript z.startsWith(value); ``` -------------------------------- ### String Parsing Benchmark (Zod 3 vs Zod 4) Source: https://zod.dev/v4 Compares the performance of z.string().parse between Zod 3 and Zod 4, showing Zod 4 is 14.71x faster. ```sh $ pnpm bench string runtime: node v22.13.0 (arm64-darwin) benchmark time (avg) (min … max) p75 p99 p999 ------------------------------------------------- ----------------------------- • z.string().parse ------------------------------------------------- ----------------------------- zod3 363 µs/iter (338 µs … 683 µs) 351 µs 467 µs 572 µs zod4 24'674 ns/iter (21'083 ns … 235 µs) 24'209 ns 76'125 ns 120 µs summary for z.string().parse zod4 14.71x faster than zod3 ``` -------------------------------- ### Upgrade to Zod 4 Source: https://zod.dev/v4/versioning Instructions for upgrading to Zod 4. This snippet shows the recommended command to update your project. ```bash npm install zod@4.0.0 ``` -------------------------------- ### Strict Object Schema Example Source: https://zod.dev/v4/changelog Defines a strict object schema where only explicitly defined properties are allowed. ```typescript z.strictObject({ name: z.string() }); ``` -------------------------------- ### Use .describe() as Shorthand for .meta() (Zod) Source: https://zod.dev/metadata Demonstrates the .describe() method in Zod as a shorthand for registering only a description in the global registry, equivalent to calling .meta({ description: ... }). ```typescript const emailSchema = z.email(); emailSchema.describe("An email address"); // equivalent to emailSchema.meta({ description: "An email address" }); ``` -------------------------------- ### Zod Literal Schema Example Source: https://zod.dev/packages/core Shows the creation of a ZodLiteral schema for validating a specific, single value. ```typescript new ZodLiteral() ``` -------------------------------- ### Configure Peer Dependencies for Zod Source: https://zod.dev/library-authors When building a library on top of Zod, include 'zod' in your 'peerDependencies' to allow users to provide their own Zod instance. Also, add 'zod' to 'devDependencies' for local development. ```json // package.json { // ... "peerDependencies": { "zod": "^4.0.0" } } ``` ```json // package.json { "peerDependencies": { "zod": "^4.0.0" }, "devDependencies": { "zod": "^4.0.0" } } ``` -------------------------------- ### Zod Schema Checks Example Source: https://zod.dev/packages/core Illustrates how to add checks to a Zod string schema, such as email validation. ```typescript const schema = z.string().check(z.email()).check( ``` -------------------------------- ### Creating a Schema with Unknown using Zod Mini Source: https://zod.dev/packages/mini Use z.unknown to create a schema that accepts any type. This is a less common but sometimes necessary option. ```javascript const unknownSchema = z.unknown(); ``` -------------------------------- ### Register Schema Metadata using .meta() (Zod Mini) Source: https://zod.dev/metadata Shows how to use the .meta() method within Zod Mini's .check() to register metadata for a schema. ```typescript const emailSchema = z.email().check( z.meta({ id: "email_address", title: "Email address", description: "Please enter a valid email address", }) ); ``` -------------------------------- ### Zod 3 Schema Definition Source: https://zod.dev/library-authors Example of defining a schema using Zod version 3 syntax. ```typescript schema._def; // Zod 3 schema ``` -------------------------------- ### User Code: Using Library Function with Zod and Zod Mini Source: https://zod.dev/library-authors Demonstrates how user code can import and use a library function that accepts schemas from both Zod and Zod Mini. ```typescript 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() })) ``` -------------------------------- ### Zod 4 Schema Definition Source: https://zod.dev/library-authors Example of defining a schema using Zod version 4 syntax. ```typescript schema._zod.def; // Zod 4 schema ``` -------------------------------- ### String Starts With Validation Source: https://zod.dev/v4 Use `z.string().startsWith(value)` to validate if a string begins with a specific prefix. ```typescript z.string().startsWith(value); ``` -------------------------------- ### Registering a Schema with a Registry Source: https://zod.dev/packages/mini Demonstrates how to register a schema within a custom registry using `z.registry` and the `.register()` method. Useful for managing schemas. ```typescript const myReg = z.registry<{title: string}>(); z.string().register(myReg, { title: "My cool string schema" }); ``` -------------------------------- ### Safe Parsing with .safeParse() Source: https://zod.dev/basics Use .safeParse() to get a result object with success/error status instead of throwing. ```typescript const result = Player.safeParse({ username: 42, xp: "100" }); if (!result.success) { result.error; // ZodError instance } else { result.data; // { username: string; xp: number } } ``` -------------------------------- ### Importing Zod Mini Source: https://zod.dev/packages/mini Import Zod Mini using the 'zod/mini' path. This allows for a tree-shakable API. ```javascript import { z } from "zod/mini"; ``` -------------------------------- ### Creating a ZodError Source: https://zod.dev/v4 This snippet shows how to instantiate a ZodError with specific error codes and keys. This is a foundational step before pretty-printing. ```typescript const myError = new z.ZodError([ { code: 'unrecognized_keys', keys: ["invalid_key"], always: true } ]); ``` -------------------------------- ### Zod .overwrite() Example Source: https://zod.dev/v4 Illustrates the .overwrite() method, which applies a transformation without changing the inferred type of the schema. ```typescript z.number().overwrite(val => val ** 2).max(100); // => ZodNumber ``` -------------------------------- ### Custom Errors with Zod Source: https://zod.dev/error-customization Examples of customizing error messages for various Zod schemas using string arguments. ```typescript z.string("Bad!"); z.string().min(5, "Too short!"); z.uuid("Bad UUID!"); z.iso.date("Bad date!"); z.array(z.string(), "Not an array!"); z.array(z.string()).min(5, "Too few items!"); z.set(z.string(), "Bad set!"); ``` -------------------------------- ### Configure Peer Dependencies Source: https://zod.dev/library-authors Libraries built on Zod should include 'zod' in their 'peerDependencies'. This allows users to manage their own Zod version. ```json { "dependencies": { // ... }, "peerDependencies": { "zod": "^3.0.0" // Or the appropriate version range } } ``` -------------------------------- ### Combine CIDR Validation Methods Source: https://zod.dev/v4/changelog Shows how to use `z.union()` to accept both IPv4 and IPv6 CIDR notations when specific methods like `cidrv4()` and `cidrv6()` are needed. ```typescript z.union([z.string().cidrv4(), z.string().cidrv6()]) ``` -------------------------------- ### Accessing Metadata Source: https://zod.dev/metadata Metadata attached via .meta() can be accessed programmatically. This example shows accessing the description from the 'A' schema. ```typescript A.meta(); // => { description: "A cool string" } ``` -------------------------------- ### Equivalent Email Schema with Metadata Source: https://zod.dev/metadata Demonstrates an alternative way to define the same email schema with metadata using the `meta` method. This is equivalent to using `describe`. ```typescript z.string().email().meta({ description: "An email address" }); ``` -------------------------------- ### Replace z.string().cidr() with z.cidrv4() and z.cidrv6() Source: https://zod.dev/v4/changelog The `z.string().cidr()` method has been removed. Use `z.cidrv4()` for IPv4 addresses and `z.cidrv6()` for IPv6 addresses. Combine them with `z.union()` if both are needed. ```typescript z.string().cidr() // ❌ z.cidrv4() // ✅ z.cidrv6() // ✅ ``` -------------------------------- ### Customizing `url` errors Source: https://zod.dev/error-customization Provide custom messages for `url` validation, guiding users when the input is not a valid URL. ```typescript import { z } from "zod"; const schema = z.string().url({ message: "Invalid URL format." }); console.log(schema.safeParse("not a url")); // { success: false, error: [Error: Invalid URL format.] } ``` -------------------------------- ### Transform string to length Source: https://zod.dev/codecs Example of transforming a string schema to validate its length. This demonstrates a common pattern for input validation. ```typescript const schema = z.string().transform(val => val.length); schema.encode(123); // ❌ Error: Encountered unidirectional transform during encode: ZodTransform ``` -------------------------------- ### Using .meta() Method Source: https://zod.dev/metadata Use the .meta() method to attach metadata to a Zod schema. This provides a convenient way to associate extra information with your schemas. ```typescript z.string().meta({ examples: [] }); ``` -------------------------------- ### Using .meta() for Schema Descriptions Source: https://zod.dev/v4 Use the .meta() method for adding descriptions and other metadata to Zod schemas. This is the preferred method over .describe() for compatibility with Zod 3. ```typescript z.string().describe("An email address"); // equivalent to z.string().meta({ description: "An email address" }); ```