1. Primitive, Coercion & String Format Constructors
This module catalogs Zod v4.6.7's scalar primitive constructors (z.string, z.number, z.int, z.bigint, z.boolean, z.date), literal and enumeration types (z.literal, z.enum, z.templateLiteral), input coercion (z.coerce), bidirectional z.stringbool, top-level string format constructors (z.email, z.uuid, z.url, z.jwt, z.ipv4, z.ipv6, z.hash), and ISO 8601 temporal schemas (z.iso.*).
Source Code
from drawlib import canvas
from drawlib.diagrams.architecture import ArchitectureDiagram, Node, NodeGroup, PhosphorIcon
from drawlib.lines import line
from drawlib.styles import Styles
from drawlib.text import text
canvas.clear()
canvas.setup(width=184, height=106, dpi=150)
text(
(92, 100.5),
"$ZodType / ZodType Primitive, Coercion & String Format Hierarchy",
style=Styles.DarkBold.patch(text_size=13.0),
)
d = ArchitectureDiagram(
node_style=Styles.PrimaryBold,
node_text_style=Styles.DarkBold.patch(text_size=10.0),
edge_style=Styles.PrimaryBold,
edge_text_style=Styles.DarkBold.patch(text_size=10.0),
node_card_style=Styles.Neutral,
)
# Root Base Class
root = d.add(
Node(
"ZodType<Output, Input> (extends core.$ZodType)\nparse / safeParse / check / refine / toJSONSchema",
width=92,
height=12.5,
icon=PhosphorIcon.TREE_STRUCTURE,
icon_size=5.8,
style=Styles.WhiteBold,
text_style=Styles.WhiteBold.patch(text_size=10.5),
card_style=Styles.PrimaryFlat,
),
xy=(88.0, 84.0),
)
# Group 1: Scalar Primitives
g_prim = d.add(
NodeGroup(title="Scalar Primitives", padding=4.5),
xy=(2.0, 4.0),
)
g_prim.add(
Node("ZodString\nz.string()", width=36, height=12.5, icon=PhosphorIcon.TEXT_T, icon_size=5.5, card_style=Styles.PrimaryNeutral),
xy=(22.5, 49.0),
)
g_prim.add(
Node("ZodNumber / ZodInt\nz.number() / z.int()", width=36, height=12.5, icon=PhosphorIcon.HASH, icon_size=5.5, card_style=Styles.Neutral),
xy=(22.5, 34.0),
)
g_prim.add(
Node("ZodBigInt / Int64\nz.bigint() / z.int64()", width=36, height=12.5, icon=PhosphorIcon.CALCULATOR, icon_size=5.5, card_style=Styles.Neutral),
xy=(22.5, 19.0),
)
g_prim.add(
Node("ZodBoolean / ZodDate\nz.boolean() / z.date()", width=36, height=12.5, icon=PhosphorIcon.CALENDAR, icon_size=5.5, card_style=Styles.Neutral),
xy=(22.5, 4.0),
)
# Group 2: Literals, Enums & Coercion
g_enum = d.add(
NodeGroup(title="Literals, Enums & Coercion", padding=4.5),
xy=(50.0, 4.0),
)
g_enum.add(
Node("ZodLiteral<T>\nz.literal(val | vals[])", width=40, height=12.5, icon=PhosphorIcon.TAG, icon_size=5.5, card_style=Styles.Neutral),
xy=(24.5, 49.0),
)
g_enum.add(
Node("ZodEnum<T>\nz.enum([...]) / extract", width=40, height=12.5, icon=PhosphorIcon.LIST_BULLETS, icon_size=5.5, card_style=Styles.PrimaryNeutral),
xy=(24.5, 34.0),
)
g_enum.add(
Node("ZodTemplateLiteral\nz.templateLiteral([...])", width=40, height=12.5, icon=PhosphorIcon.CODE, icon_size=5.5, card_style=Styles.Neutral),
xy=(24.5, 19.0),
)
g_enum.add(
Node("z.coerce.* & z.stringbool()\nInput Coercion & Bool Codec", width=40, height=12.5, icon=PhosphorIcon.ARROWS_CLOCKWISE, icon_size=5.5, card_style=Styles.SecondaryNeutral),
xy=(24.5, 4.0),
)
# Group 3: ZodStringFormat Subclasses (v4 Top-Level Formats)
g_fmt = d.add(
NodeGroup(title="ZodStringFormat<Format> Subclasses", padding=4.5),
xy=(102.0, 4.0),
)
g_fmt.add(
Node("ZodEmail / ZodUUID / ULID\nz.email() / z.uuid() / z.cuid2()", width=66, height=12.5, icon=PhosphorIcon.FINGERPRINT, icon_size=5.5, style=Styles.WhiteBold, text_style=Styles.WhiteBold.patch(text_size=10.0), card_style=Styles.AccentFlat),
xy=(37.5, 49.0),
)
g_fmt.add(
Node("ZodURL / ZodIPv4 / ZodIPv6\nz.url() / z.httpUrl() / z.cidrv4()", width=66, height=12.5, icon=PhosphorIcon.GLOBE, icon_size=5.5, card_style=Styles.PrimaryNeutral),
xy=(37.5, 34.0),
)
g_fmt.add(
Node("ZodJWT / ZodBase64 / Hash\nz.jwt() / z.base64url() / z.hash()", width=66, height=12.5, icon=PhosphorIcon.SHIELD_CHECK, icon_size=5.5, card_style=Styles.Neutral),
xy=(37.5, 19.0),
)
g_fmt.add(
Node("ZodISODateTime / Date / Time\nz.iso.datetime() / date / duration", width=66, height=12.5, icon=PhosphorIcon.CLOCK, icon_size=5.5, card_style=Styles.PrimaryNeutral),
xy=(37.5, 4.0),
)
d.draw(xy=(4.0, 2.0))
# Top-down tree bus from ZodType root (center x=92, bottom y=79.5) to the top of each group (y=68.5)
line((92.0, 79.5), (92.0, 74.5), style=Styles.PrimaryBold)
line((28.5, 74.5), (143.5, 74.5), style=Styles.PrimaryBold)
line((28.5, 74.5), (28.5, 68.5), arrow_head="->", style=Styles.PrimaryBold)
line((78.5, 74.5), (78.5, 68.5), arrow_head="->", style=Styles.PrimaryBold)
line((143.5, 74.5), (143.5, 68.5), arrow_head="->", style=Styles.PrimaryBold)
canvas.save()
functionz.string#
Constructs a ZodString schema that validates typeof input === "string". Includes built-in length checks, substring/regex validators, and in-place string normalization transforms.
function z.string(params?: string | core.$ZodStringParams): ZodString
| Parameter / Property / Method | Signature | Description |
|---|---|---|
params |
string | { error?: string | $ZodErrorMap } |
Custom error message string or per-issue error map callback. |
.min(n, params?) / .max(n, params?) |
(len: number, params?) => this |
Validates input.length >= n (too_small) or input.length <= n (too_big). |
.length(n, params?) |
(len: number, params?) => this |
Validates exact character length input.length === n. |
.nonempty(params?) |
(params?) => this |
Equivalent to .min(1, params). |
.regex(re, params?) |
(regex: RegExp, params?) => this |
Validates that input matches the provided RegExp. |
.includes(sub, params?) |
(value: string, params?: { position?: number }) => this |
Checks input.includes(value, position). |
.startsWith(p, params?) / .endsWith(s, params?) |
(value: string, params?) => this |
Checks prefix (startsWith) or suffix (endsWith). |
.lowercase(params?) / .uppercase(params?) |
(params?) => this |
Validation check asserting all characters are already lower- or uppercase. |
.trim() |
() => this |
Mutating check that strips leading and trailing whitespace (input.trim()). |
.toLowerCase() / .toUpperCase() |
() => this |
Mutating check that converts output case in-place. |
.normalize(form?) |
(form?: "NFC" | "NFD" | "NFKC" | "NFKD") => this |
Applies Unicode normalization (input.normalize(form)). |
.slugify() |
() => this |
Converts string into a lowercase URL-safe hyphenated ASCII slug. |
.minLength / .maxLength / .format |
number | null / string | null |
Read-only getters aggregating attached length and format checks. |
import { z } from "zod";
const Username = z
.string("Username is required")
.trim()
.toLowerCase()
.min(3, "Must be at least 3 chars")
.max(24)
.regex(/^[a-z0-9_]+$/, "Only lowercase letters, digits, and underscores");
Username.parse(" Alice_42 "); // => "alice_42"
functionz.number#
Constructs a ZodNumber schema that validates finite IEEE-754 floating-point numbers (typeof input === "number" && Number.isFinite(input)). Unlike Zod v3, Infinity, -Infinity, and NaN are rejected by default.
function z.number(params?: string | core.$ZodNumberParams): ZodNumber
| Method / Property | Signature | Description |
|---|---|---|
.gt(val, params?) |
(value: number, params?) => this |
Strictly greater than (input > value, inclusive: false). |
.gte(val, params?) / .min(val, params?) |
(value: number, params?) => this |
Greater than or equal to (input >= value, inclusive: true). |
.lt(val, params?) |
(value: number, params?) => this |
Strictly less than (input < value, inclusive: false). |
.lte(val, params?) / .max(val, params?) |
(value: number, params?) => this |
Less than or equal to (input <= value, inclusive: true). |
.positive(params?) / .nonnegative(params?) |
(params?) => this |
Shorthand for .gt(0) (> 0) and .gte(0) (>= 0). |
.negative(params?) / .nonpositive(params?) |
(params?) => this |
Shorthand for .lt(0) (< 0) and .lte(0) (<= 0). |
.multipleOf(step, params?) |
(value: number, params?) => this |
Validates input % value === 0 with float-safe epsilon handling. |
.int(params?) |
(params?) => this |
Appends a safe integer check (Number.isSafeInteger). Prefer z.int() for standalone integer schemas. |
.minValue / .maxValue / .format |
number | null / string | null |
Read-only getters inspecting aggregated numeric bounds and format. |
import { z } from "zod";
const Price = z.number().nonnegative().multipleOf(0.01);
Price.parse(19.99); // => 19.99
Price.safeParse(Number.POSITIVE_INFINITY).success; // => false
functionz.int#
Constructs a ZodNumberFormat schema restricting numbers to specific integer or IEEE-754 bit-width ranges and emitting a matching format in JSON Schema.
function z.int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt
function z.int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32
function z.uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32
function z.float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32
function z.float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64
| Constructor | Return Class | Validated Range | JSON Schema Output |
|---|---|---|---|
z.int(params?) |
ZodInt (ZodNumberFormat<"safeint">) |
[-(2^53 - 1), 2^53 - 1] (Number.MIN_SAFE_INTEGER..MAX_SAFE_INTEGER) |
{ type: "integer" } |
z.int32(params?) |
ZodInt32 (ZodNumberFormat<"int32">) |
[-2,147,483,648, 2,147,483,647] (-2^31..2^31 - 1) |
{ type: "integer", format: "int32" } |
z.uint32(params?) |
ZodUInt32 (ZodNumberFormat<"uint32">) |
[0, 4,294,967,295] (0..2^32 - 1) |
{ type: "integer", format: "uint32" } |
z.float32(params?) |
ZodFloat32 (ZodNumberFormat<"float32">) |
[-3.4028234663852886e+38, 3.4028234663852886e+38] |
{ type: "number", format: "float" } |
z.float64(params?) |
ZodFloat64 (ZodNumberFormat<"float64">) |
[-Number.MAX_VALUE, Number.MAX_VALUE] |
{ type: "number", format: "double" } |
import { z } from "zod";
const Port = z.uint32().min(1024).max(65535);
Port.parse(8080); // => 8080
functionz.bigint#
Constructs a ZodBigInt schema validating typeof input === "bigint", along with 64-bit signed (z.int64) and unsigned (z.uint64) format constructors.
function z.bigint(params?: string | core.$ZodBigIntParams): ZodBigInt
function z.int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64
function z.uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64
| Constructor / Method | Signature / Range | Description |
|---|---|---|
z.bigint(params?) |
ZodBigInt |
Arbitrary-precision JavaScript bigint. |
z.int64(params?) |
ZodInt64 ([-2^63, 2^63 - 1]) |
Signed 64-bit integer range (-9223372036854775808n..9223372036854775807n). |
z.uint64(params?) |
ZodUInt64 ([0n, 2^64 - 1]) |
Unsigned 64-bit integer range (0n..18446744073709551615n). |
.gt(v) / .gte(v) / .min(v) |
(value: bigint, params?) => this |
Lower-bound bigint comparison checks. |
.lt(v) / .lte(v) / .max(v) |
(value: bigint, params?) => this |
Upper-bound bigint comparison checks. |
.positive() / .nonnegative() / .negative() / .nonpositive() |
(params?) => this |
Sign checks relative to 0n. |
.multipleOf(v, params?) |
(value: bigint, params?) => this |
Validates input % value === 0n. |
import { z } from "zod";
const SnowflakeId = z.uint64();
SnowflakeId.parse(175928847299117063n);
functionz.boolean#
Constructs a ZodBoolean schema that strictly validates typeof input === "boolean".
function z.boolean(params?: string | core.$ZodBooleanParams): ZodBoolean
| Parameter | Type | Description |
|---|---|---|
params |
string | { error?: string | $ZodErrorMap } |
Optional custom error message or error map when input is not true or false. |
import { z } from "zod";
const IsActive = z.boolean("Active flag must be a boolean");
IsActive.parse(true); // => true
functionz.stringbool#
Constructs a bidirectional ZodCodec<ZodString, ZodBoolean> that decodes environment-variable style boolean strings ("true", "1", "yes", "on", "false", "0", "no", "off") into boolean and encodes boolean back to the primary truthy/falsy string ("true" / "false").
function z.stringbool(params?: string | core.$ZodStringBoolParams): ZodCodec<ZodString, ZodBoolean>
Option ($ZodStringBoolParams) |
Type | Default | Description |
|---|---|---|---|
truthy |
string[] |
["true", "1", "yes", "on", "y", "enabled"] |
Strings that decode to true (truthy[0] is emitted on .encode(true)). |
falsy |
string[] |
["false", "0", "no", "off", "n", "disabled"] |
Strings that decode to false (falsy[0] is emitted on .encode(false)). |
case |
"sensitive" | "insensitive" |
"insensitive" |
Whether string comparison is case-sensitive or case-insensitive. |
error |
string | $ZodErrorMap |
undefined |
Custom error message or map for unrecognized string values. |
import { z } from "zod";
const EnvFlag = z.stringbool({ truthy: ["true", "1"], falsy: ["false", "0"] });
EnvFlag.parse("1"); // => true
EnvFlag.encode(false); // => "false"
functionz.date#
Constructs a ZodDate schema validating input instanceof Date && !Number.isNaN(input.getTime()). Rejects Invalid Date instances.
function z.date(params?: string | core.$ZodDateParams): ZodDate
| Method | Signature | Description |
|---|---|---|
.min(dateOrEpoch, params?) |
(value: Date | number, params?) => this |
Validates input.getTime() >= new Date(value).getTime(). |
.max(dateOrEpoch, params?) |
(value: Date | number, params?) => this |
Validates input.getTime() <= new Date(value).getTime(). |
import { z } from "zod";
constLaunchDate = z.date().min(new Date("2025-01-01T00:00:00Z"));
functionz.literal#
Constructs a ZodLiteral<T> schema matching one or more exact primitive values (string | number | bigint | boolean | null | undefined). In Zod v4, passing an array of literals z.literal(["a", "b"]) creates a single O(1) Set-backed ZodLiteral instead of requiring z.union().
function z.literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>
function z.literal<const T extends ReadonlyArray<util.Literal>>(values: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>
| Property | Type | Description |
|---|---|---|
.values |
Set<T> |
The Set of accepted literal values. |
.value |
T |
Legacy single-value getter (throws if .values.size > 1). |
import { z } from "zod";
const HttpStatus = z.literal([200, 201, 204]);
type Status = z.infer<typeof HttpStatus>; // 200 | 201 | 204
functionz.enum#
Constructs a ZodEnum<T> schema from either a readonly string[] tuple or a TypeScript enum / const object (unifying Zod v3's z.enum() and z.nativeEnum()).
function z.enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>
function z.enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>
| Property / Method | Signature | Description |
|---|---|---|
.enum |
T |
Key-to-value lookup object (e.g. Role.enum.admin === "admin"). |
.options |
Array<T[keyof T]> |
Array of valid enum values (excludes reverse-mapped numeric keys on TS numeric enums). |
.extract(keys, params?) |
<U extends readonly (keyof T)[]>(values: U, params?) => ZodEnum<Pick<T, U[number]>> |
Creates a narrowed ZodEnum containing only the specified keys. |
.exclude(keys, params?) |
<U extends readonly (keyof T)[]>(values: U, params?) => ZodEnum<Omit<T, U[number]>> |
Creates a narrowed ZodEnum omitting the specified keys. |
import { z } from "zod";
const Role = z.enum(["admin", "editor", "viewer"]);
const StaffRole = Role.exclude(["viewer"]); // ZodEnum<{ admin: "admin"; editor: "editor" }>
functionz.templateLiteral#
Constructs a ZodTemplateLiteral<Template> schema that compiles an array of literal primitives and inner schemas (z.string(), z.number(), z.int(), z.boolean(), z.literal(), z.enum(), etc.) into an exact TypeScript template literal type and composite regular expression.
function z.templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(
parts: Parts,
params?: string | core.$ZodTemplateLiteralParams
): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>
import { z } from "zod";
const CssUnit = z.templateLiteral([z.number(), z.enum(["px", "rem", "vh", "vw"])]);
type CssUnit = z.infer<typeof CssUnit>; // `${number}px` | `${number}rem` | `${number}vh` | `${number}vw`
CssUnit.parse("16px"); // => "16px"
namespace z.coerce#
The z.coerce namespace provides primitive constructors that coerce unknown input via JavaScript's built-in constructor (String(x), Number(x), Boolean(x), BigInt(x), new Date(x)) before running schema validation. In Zod v4, the inferred input type z.input<typeof schema> defaults to unknown (and can be explicitly parameterized via z.coerce.number<string | number>()).
namespace z.coerce {
function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T>;
function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T>;
function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T>;
function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T>;
function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T>;
}
import { z } from "zod";
const PageQuery = z.coerce.number<string | number>().int().min(1);
PageQuery.parse("42"); // => 42
functionz.email#
In Zod v4, string formats are promoted to first-class top-level constructors returning subclasses of ZodStringFormat<Format> for optimal tree-shaking and clean type hierarchy.
Source Code
from drawlib.canvas import save, setup
from drawlib.smartarts import Table
from drawlib.styles import Colors, Styles
from drawlib.text import text
setup(width=186, height=90, dpi=150)
text(
(93, 85.5),
"Zod v4.6.7 Top-Level String Format & z.iso.* Constructors",
style=Styles.DarkBold.patch(text_size=12.5),
)
table = Table(
cell_style=Styles.White,
text_style=Styles.Dark.patch(text_size=10.0),
header_cell_style=Styles.PrimaryFlat,
header_text_style=Styles.WhiteBold.patch(text_size=10.5),
border_style=Styles.MutedThin,
)
table.set_style_cell_evenodd(
even_color=Colors.Light,
even_text_style=Styles.Dark.patch(text_size=10.0),
odd_color=Colors.White,
odd_text_style=Styles.Dark.patch(text_size=10.0),
)
table.set_style_cell_header(
background_color=Colors.Primary,
text_style=Styles.WhiteBold.patch(text_size=10.5),
)
table.set_style_cell(
background_color=Colors.Light,
text_style=Styles.PrimaryBold.patch(text_size=10.0),
rows=[1, 2, 3, 4, 5, 6, 7, 8, 9],
columns=[0],
)
data = [
["Constructor", "Return Class", "Format Options (params)", "JSON Schema format"],
["z.email(params?)", "ZodEmail", "pattern?: RegExp (gmail/html5/rfc5322)", '"email"'],
["z.uuid() / z.uuidv4..v7()", "ZodUUID", 'version?: "v1".."v8" (RFC 9562)', '"uuid"'],
["z.nanoid / cuid2 / ulid", "ZodNanoID / CUID2 / ULID", "length?: number (on z.nanoid)", '"nanoid" / "cuid2" / "ulid"'],
["z.url() / z.httpUrl()", "ZodURL", "protocol?: RegExp, hostname?: RegExp, normalize?", '"uri"'],
["z.jwt(params?)", "ZodJWT", 'alg?: JWTAlgorithm ("HS256", "RS256", ...)', '"jwt"'],
["z.ipv4() / z.ipv6() / cidr*", "ZodIPv4 / IPv6 / CIDR*", "Strict IPv4/IPv6 & CIDR prefix validation", '"ipv4" / "ipv6" / "cidrv4"'],
["z.hash(alg, params?)", "ZodCustomStringFormat", 'alg: "md5"|"sha1"|"sha256"|"sha384"|"sha512", enc?', '"<alg>_<enc>"'],
["z.iso.datetime(params?)", "ZodISODateTime", "offset?: bool, local?: bool, precision?: number", '"date-time"'],
["z.iso.date / time / duration", "ZodISODate / Time / Duration", "precision?: number (on z.iso.time)", '"date" / "time" / "duration"'],
]
table.draw_flexible(
xy=(4, 80),
column_widths=[38, 36, 68, 36],
row_heights=[8.0, 7.2, 7.2, 7.2, 7.2, 7.2, 7.2, 7.2, 7.2, 7.2],
data=data,
align="top_left",
)
save()
z.email() validates email addresses and allows overriding the regex pattern via z.regexes.*:
function z.email(params?: string | core.$ZodEmailParams): ZodEmail
Option ($ZodEmailParams) |
Type | Default | Description |
|---|---|---|---|
pattern |
RegExp |
z.regexes.email |
Custom email regex (z.regexes.email, z.regexes.html5Email, z.regexes.rfc5322Email, z.regexes.unicodeEmail, or z.regexes.browserEmail). |
error |
string | $ZodErrorMap |
undefined |
Custom error message or callback. |
import { z } from "zod";
const CorpEmail = z.email({ pattern: z.regexes.html5Email });
functionz.uuid#
Validates RFC 9562 / RFC 4122 UUID strings and related distributed identifier formats (guid, nanoid, cuid2, ulid, xid, ksuid).
function z.uuid(params?: string | core.$ZodUUIDParams): ZodUUID
function z.uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID
function z.uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID
function z.uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID
function z.guid(params?: string | core.$ZodGUIDParams): ZodGUID
function z.nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID
function z.cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2
function z.ulid(params?: string | core.$ZodULIDParams): ZodULID
function z.xid(params?: string | core.$ZodXIDParams): ZodXID
function z.ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID
| Constructor | Options | Description |
|---|---|---|
z.uuid(params?) |
{ version?: "v1" | "v2" | "v3" | "v4" | "v5" | "v6" | "v7" | "v8" } |
Validates strict RFC 9562 UUID (optionally pinned to a specific version). |
z.uuidv4() / z.uuidv6() / z.uuidv7() |
string | { error? } |
Dedicated convenience constructors pinning version to "v4", "v6", or "v7". |
z.guid(params?) |
string | { error? } |
Permissive 8-4-4-4-12 hex format without version/variant bit restrictions. |
z.nanoid(params?) |
{ length?: number, error? } |
Validates URL-safe NanoID strings (defaults to 21 chars; customizable via length). |
z.cuid2() / z.ulid() / z.xid() / z.ksuid() |
string | { error? } |
Validates collision-resistant sortable identifiers. |
import { z } from "zod";
const EventId = z.uuidv7();
const ShortId = z.nanoid({ length: 12 });
functionz.url#
Validates URLs using the WHATWG URL parser with optional protocol and hostname regular expression guards and optional WHATWG .href normalization. z.httpUrl() pre-configures protocol: /^https?$/i and hostname: z.regexes.domain for web URLs.
function z.url(params?: string | core.$ZodURLParams): ZodURL
function z.httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL
Option ($ZodURLParams) |
Type | Default | Description |
|---|---|---|---|
protocol |
RegExp |
undefined |
Regex tested against url.protocol without the trailing colon (e.g. /^https$/). |
hostname |
RegExp |
undefined |
Regex tested against url.hostname (e.g. /\.example\.com$/). |
normalize |
boolean |
false |
When true, normalizes the output string to new URL(input).href. |
import { z } from "zod";
const WebhookUrl = z.url({
protocol: /^https$/,
hostname: z.regexes.domain,
normalize: true,
});
functionz.jwt#
Validates JSON Web Tokens (3-part base64url structure with valid JSON header and alg claim), alongside encoding, cryptographic hash, and telecom/finance string formats.
function z.jwt(params?: string | core.$ZodJWTParams): ZodJWT
function z.base64(params?: string | core.$ZodBase64Params): ZodBase64
function z.base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL
function z.hex(params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">
function z.hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(
alg: Alg,
params?: { enc?: Enc } & core.$ZodStringFormatParams
): ZodCustomStringFormat<`${Alg}_${Enc}`>
function z.e164(params?: string | core.$ZodE164Params): ZodE164
function z.creditCard(params?: string | core.$ZodCreditCardParams): ZodCreditCard
function z.iban(params?: string | core.$ZodIBANParams): ZodIBAN
| Constructor | Options / Parameters | Validation Behavior |
|---|---|---|
z.jwt(params?) |
{ alg?: JWTAlgorithm, error? } |
Verifies 3 base64url segments, decodes header JSON, checks typ: "JWT" (if present) and alg. |
z.base64() / z.base64url() |
string | { error? } |
Linear-time O(n) charset + padding validation (immune to multi-MB regex stack overflow). |
z.hash(alg, params?) |
alg: "md5" | "sha1" | "sha256" | "sha384" | "sha512", enc?: "hex" | "base64" | "base64url" |
Validates exact digest length and encoding alphabet (e.g. z.hash("sha256")). |
z.e164() / z.creditCard() / z.iban() |
string | { error? } |
Validates E.164 phone numbers, Luhn credit cards, and ISO 7064 Mod 97-10 IBANs. |
import { z } from "zod";
const BearerJwt = z.jwt({ alg: "RS256" });
const CommitSha256 = z.hash("sha256", { enc: "hex" });
functionz.ipv4 & z.ipv6#
Validates network addresses, CIDR blocks, MAC addresses, and DNS hostnames:
function z.ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4
function z.ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6
function z.cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4
function z.cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6
function z.mac(params?: string | core.$ZodMACParams): ZodMAC
function z.hostname(params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">
function z.stringFormat<Format extends string>(
format: Format,
fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp,
params?: string | core.$ZodStringFormatParams
): ZodCustomStringFormat<Format>
| Constructor | Options | Description |
|---|---|---|
z.ipv4() / z.ipv6() |
string | { error? } |
Validates dotted-quad IPv4 or RFC 4291 IPv6 addresses. |
z.cidrv4() / z.cidrv6() |
string | { error? } |
Validates IPv4 CIDR (/0../32) or IPv6 CIDR (/0../128) blocks. |
z.mac(params?) |
{ delimiter?: string, error? } |
Validates 6-octet IEEE 802 MAC address (customizable delimiter, default : or -). |
z.stringFormat(name, fnOrRegex, params?) |
Custom format name + validator | Creates a user-defined ZodCustomStringFormat<Format> with custom predicate or RegExp. |
import { z } from "zod";
const Subnet = z. union([z.cidrv4(), z.cidrv6()]);
const MacColon = z.mac({ delimiter: ":" });
namespace z.iso#
The z.iso namespace provides strict ISO 8601 date, time, datetime, and duration string schemas (ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration).
namespace z.iso {
function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime;
function date(params?: string | core.$ZodISODateParams): ZodISODate;
function time(params?: string | core.$ZodISOTimeParams): ZodISOTime;
function duration(params?: string | core.$ZodISODurationParams): ZodISODuration;
}
| Constructor | Options (params) |
Default Behavior |
|---|---|---|
z.iso.datetime(params?) |
{ offset?: boolean, local?: boolean, precision?: number | null } |
Requires trailing Z by default; offset: true allows ±HH:MM; local: true allows unqualified local datetimes; precision (TimePrecision) pins fractional second digits (-1 minute, 0 sec, 3 ms, 6 µs). |
z.iso.date(params?) |
string | { error? } |
Validates YYYY-MM-DD calendar dates with leap-year and days-per-month checks. |
z.iso.time(params?) |
{ precision?: number | null, error? } |
Validates HH:MM:SS[.sss] 24-hour wall-clock time without timezone offset. |
z.iso.duration(params?) |
string | { error? } |
Validates ISO 8601 duration strings (P3Y6M4DT12H30M5S, PT15M, P4W). |
import { z } from "zod";
const Timestamp = z.iso.datetime({ offset: true, precision: z.TimePrecision.Millisecond });
Timestamp.parse("2026-11-10T10:30:00.123+09:00");
functionz.any / z.unknown / z.never / z.void / z.nan#
Special-purpose bottom, top, unit, symbol, and Web File schemas:
function z.any(): ZodAny
function z.unknown(): ZodUnknown
function z.never(params?: string | core.$ZodNeverParams): ZodNever
function z.void(params?: string | core.$ZodVoidParams): ZodVoid
function z.undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined
function z.null(params?: string | core.$ZodNullParams): ZodNull
function z.nan(params?: string | core.$ZodNaNParams): ZodNaN
function z.symbol(params?: string | core.$ZodSymbolParams): ZodSymbol
function z.file(params?: string | core.$ZodFileParams): ZodFile
| Constructor | Inferred Type | Runtime Validation |
|---|---|---|
z.any() / z.unknown() |
any / unknown |
Always succeeds on any value without runtime inspection. |
z.never(params?) |
never |
Always fails with invalid_type (expected: "never"). |
z.void(params?) / z.undefined(params?) |
void / undefined |
Validates input === undefined. |
z.null(params?) |
null |
Validates input === null. |
z.nan(params?) |
number |
Validates Number.isNaN(input). |
z.symbol(params?) |
symbol |
Validates typeof input === "symbol". |
z.file(params?) |
File |
Validates input instanceof File with .min(bytes), .max(bytes), and .mime(types) methods. |
import { z } from "zod";
const AvatarUpload = z
.file()
.min(1024)
.max(5 * 1024 * 1024)
.mime(["image/png", "image/webp"]);