1. プリミティブ・型変換・文字列フォーマットコンストラクタ
本モジュールでは、Zod v4.6.7 のスカラープリミティブコンストラクタ(z.string、z.number、z.int、z.bigint、z.boolean、z.date)、リテラルおよび列挙型(z.literal、z.enum、z.templateLiteral)、入力型変換(z.coerce)、双方向 z.stringbool、トップレベル文字列フォーマットコンストラクタ(z.email、z.uuid、z.url、z.jwt、z.ipv4、z.ipv6、z.hash)、および ISO 8601 日時スキーマ(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 プリミティブ・型変換・文字列フォーマット階層",
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> (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="スカラープリミティブ", 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="リテラル・Enum・型変換", 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()\n入力型変換 & 真偽値 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> サブクラス", 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#
typeof input === "string" を検証する ZodString スキーマを構築します。文字数チェック、部分文字列・正規表現バリデータ、およびインプレースの文字列正規化トランスフォームを提供します。
function z.string(params?: string | core.$ZodStringParams): ZodString
| パラメータ / プロパティ / メソッド | シグネチャ | 説明 |
|---|---|---|
params |
string | { error?: string | $ZodErrorMap } |
カスタムエラー文字列、または Issue ごとのエラーマップ関数。 |
.min(n, params?) / .max(n, params?) |
(len: number, params?) => this |
input.length >= n(too_small)または input.length <= n(too_big)を検証します。 |
.length(n, params?) |
(len: number, params?) => this |
厳密な文字数 input.length === n を検証します。 |
.nonempty(params?) |
(params?) => this |
.min(1, params) と同等です。 |
.regex(re, params?) |
(regex: RegExp, params?) => this |
指定された正規表現 RegExp との一致を検証します。 |
.includes(sub, params?) |
(value: string, params?: { position?: number }) => this |
input.includes(value, position) を検証します。 |
.startsWith(p, params?) / .endsWith(s, params?) |
(value: string, params?) => this |
プレフィックス(startsWith)またはサフィックス(endsWith)を検証します。 |
.lowercase(params?) / .uppercase(params?) |
(params?) => this |
すべての文字が小文字(または大文字)であることを検証します。 |
.trim() |
() => this |
先頭・末尾の空白を除去する変換チェック(input.trim())。 |
.toLowerCase() / .toUpperCase() |
() => this |
文字列を小文字または大文字へインプレース変換します。 |
.normalize(form?) |
(form?: "NFC" | "NFD" | "NFKC" | "NFKD") => this |
Unicode 正規化(input.normalize(form))を適用します。 |
.slugify() |
() => this |
文字列を URL セーフな小文字ハイフン区切りの ASCII スラッグに変換します。 |
.minLength / .maxLength / .format |
number | null / string | null |
付与された長さ制約およびフォーマットを集約して返す読み取り専用ゲッター。 |
import { z } from "zod";
const Username = z
.string("ユーザー名は必須です")
.trim()
.toLowerCase()
.min(3, "3文字以上で入力してください")
.max(24)
.regex(/^[a-z0-9_]+$/, "半角英小文字・数字・アンダースコアのみ使用可能です");
Username.parse(" Alice_42 "); // => "alice_42"
functionz.number#
有限の IEEE-754 浮動小数点数(typeof input === "number" && Number.isFinite(input))を検証する ZodNumber スキーマを構築します。Zod v3 と異なり、Infinity、-Infinity、NaN はデフォルトで拒否されます。
function z.number(params?: string | core.$ZodNumberParams): ZodNumber
| メソッド / プロパティ | シグネチャ | 説明 |
|---|---|---|
.gt(val, params?) |
(value: number, params?) => this |
より大きい(input > value, inclusive: false)。 |
.gte(val, params?) / .min(val, params?) |
(value: number, params?) => this |
以上(input >= value, inclusive: true)。 |
.lt(val, params?) |
(value: number, params?) => this |
より小さい(input < value, inclusive: false)。 |
.lte(val, params?) / .max(val, params?) |
(value: number, params?) => this |
以下(input <= value, inclusive: true)。 |
.positive(params?) / .nonnegative(params?) |
(params?) => this |
.gt(0)(> 0)および .gte(0)(>= 0)のショートハンド。 |
.negative(params?) / .nonpositive(params?) |
(params?) => this |
.lt(0)(< 0)および .lte(0)(<= 0)のショートハンド。 |
.multipleOf(step, params?) |
(value: number, params?) => this |
浮動小数点誤差を考慮して input % value === 0 を検証します。 |
.int(params?) |
(params?) => this |
安全な整数チェック(Number.isSafeInteger)を追加します。単体の整数スキーマには z.int() を推奨します。 |
.minValue / .maxValue / .format |
number | null / string | null |
集約された最小値・最大値・数値フォーマットを参照するゲッター。 |
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#
特定の整数または IEEE-754 ビット幅の範囲に数値を制限し、JSON Schema 変換時に対応する format を出力する ZodNumberFormat スキーマを構築します。
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
| コンストラクタ | 戻り値クラス | 検証される数値範囲 | JSON Schema 出力 |
|---|---|---|---|
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#
typeof input === "bigint" を検証する ZodBigInt スキーマ、および 64 ビット符号付き(z.int64)・符号なし(z.uint64)フォーマットスキーマを構築します。
function z.bigint(params?: string | core.$ZodBigIntParams): ZodBigInt
function z.int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64
function z.uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64
| コンストラクタ / メソッド | シグネチャ / 範囲 | 説明 |
|---|---|---|
z.bigint(params?) |
ZodBigInt |
任意精度の JavaScript bigint。 |
z.int64(params?) |
ZodInt64 ([-2^63, 2^63 - 1]) |
符号付き 64 ビット整数範囲(-9223372036854775808n..9223372036854775807n)。 |
z.uint64(params?) |
ZodUInt64 ([0n, 2^64 - 1]) |
符号なし 64 ビット整数範囲(0n..18446744073709551615n)。 |
.gt(v) / .gte(v) / .min(v) |
(value: bigint, params?) => this |
下限値の bigint 比較チェック。 |
.lt(v) / .lte(v) / .max(v) |
(value: bigint, params?) => this |
上限値の bigint 比較チェック。 |
.positive() / .nonnegative() / .negative() / .nonpositive() |
(params?) => this |
0n を基準とした符号チェック。 |
.multipleOf(v, params?) |
(value: bigint, params?) => this |
input % value === 0n を検証します。 |
import { z } from "zod";
const SnowflakeId = z.uint64();
SnowflakeId.parse(175928847299117063n);
functionz.boolean#
typeof input === "boolean" を厳密に検証する ZodBoolean スキーマを構築します。
function z.boolean(params?: string | core.$ZodBooleanParams): ZodBoolean
| パラメータ | 型 | 説明 |
|---|---|---|
params |
string | { error?: string | $ZodErrorMap } |
入力が true または false でない場合のカスタムエラーメッセージまたはエラーマップ。 |
import { z } from "zod";
const IsActive = z.boolean("有効フラグは真偽値で指定してください");
IsActive.parse(true); // => true
functionz.stringbool#
環境変数形式の真偽値文字列("true", "1", "yes", "on", "false", "0", "no", "off")を boolean にデコードし、boolean を代表文字列("true" / "false")へ逆エンコードする双方向 ZodCodec<ZodString, ZodBoolean> を構築します。
function z.stringbool(params?: string | core.$ZodStringBoolParams): ZodCodec<ZodString, ZodBoolean>
オプション ($ZodStringBoolParams) |
型 | デフォルト値 | 説明 |
|---|---|---|---|
truthy |
string[] |
["true", "1", "yes", "on", "y", "enabled"] |
true にデコードされる文字列リスト(.encode(true) 時は truthy[0] を出力)。 |
falsy |
string[] |
["false", "0", "no", "off", "n", "disabled"] |
false にデコードされる文字列リスト(.encode(false) 時は falsy[0] を出力)。 |
case |
"sensitive" | "insensitive" |
"insensitive" |
大文字・小文字を区別するかどうか。 |
error |
string | $ZodErrorMap |
undefined |
未登録の文字列が渡された際のカスタムエラー指定。 |
import { z } from "zod";
const EnvFlag = z.stringbool({ truthy: ["true", "1"], falsy: ["false", "0"] });
EnvFlag.parse("1"); // => true
EnvFlag.encode(false); // => "false"
functionz.date#
input instanceof Date && !Number.isNaN(input.getTime()) を検証する ZodDate スキーマを構築します。Invalid Date インスタンスは拒否されます。
function z.date(params?: string | core.$ZodDateParams): ZodDate
| メソッド | シグネチャ | 説明 |
|---|---|---|
.min(dateOrEpoch, params?) |
(value: Date | number, params?) => this |
input.getTime() >= new Date(value).getTime() を検証します。 |
.max(dateOrEpoch, params?) |
(value: Date | number, params?) => this |
input.getTime() <= new Date(value).getTime() を検証します。 |
import { z } from "zod";
const LaunchDate = z.date().min(new Date("2025-01-01T00:00:00Z"));
functionz.literal#
1 つ以上のプリミティブリテラル値(string | number | bigint | boolean | null | undefined)との完全一致を検証する ZodLiteral<T> スキーマを構築します。Zod v4 では配列 z.literal(["a", "b"]) を渡すことで、z.union() を使わずに単一の O(1) Set ベースの ZodLiteral を構成できます。
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]>
| プロパティ | 型 | 説明 |
|---|---|---|
.values |
Set<T> |
許可されたリテラル値の Set。 |
.value |
T |
単一リテラル値用のレガシーゲッター(.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#
readonly string[] タプル、または TypeScript の enum / as const オブジェクトから ZodEnum<T> スキーマを構築します(Zod v3 の z.enum() と 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>
| プロパティ / メソッド | シグネチャ | 説明 |
|---|---|---|
.enum |
T |
キーから値を引くルックアップオブジェクト(例: Role.enum.admin === "admin")。 |
.options |
Array<T[keyof T]> |
有効な列挙値の配列(数値 TS enum の逆マッピングキーは自動的に除外されます)。 |
.extract(keys, params?) |
<U extends readonly (keyof T)[]>(values: U, params?) => ZodEnum<Pick<T, U[number]>> |
指定したキーのみを抽出した新しい ZodEnum を返します。 |
.exclude(keys, params?) |
<U extends readonly (keyof T)[]>(values: U, params?) => ZodEnum<Omit<T, U[number]>> |
指定したキーを除外した新しい ZodEnum を返します。 |
import { z } from "zod";
const Role = z.enum(["admin", "editor", "viewer"]);
const StaffRole = Role.exclude(["viewer"]); // ZodEnum<{ admin: "admin"; editor: "editor" }>
functionz.templateLiteral#
リテラル値や内部スキーマ(z.string(), z.number(), z.int(), z.boolean(), z.literal(), z.enum() など)の配列から、TypeScript のテンプレートリテラル型と合成正規表現を同時に生成する ZodTemplateLiteral<Template> スキーマを構築します。
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#
z.coerce 名前空間は、スキーマ検証の前に JavaScript の組み込みコンストラクタ(String(x), Number(x), Boolean(x), BigInt(x), new Date(x))で入力値を型変換するプリミティブコンストラクタ群を提供します。Zod v4 では推論される入力型 z.input<typeof schema> のデフォルトが unknown となり、必要に応じて 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#
Zod v4 では、文字列フォーマット群が ZodStringFormat<Format> のサブクラスを返すトップレベル関数へと昇格し、Tree-Shaking 効率と型階層の明確性が大幅に向上しました。
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 トップレベル文字列フォーマット & z.iso.* コンストラクタ対応表",
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 = [
["コンストラクタ", "戻り値クラス", "主なフォーマットオプション (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 (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*", "厳密な IPv4/IPv6 および CIDR プレフィックス検証", '"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 (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() はメールアドレスを検証し、z.regexes.* プリセットによる正規表現の切り替えをサポートします。
function z.email(params?: string | core.$ZodEmailParams): ZodEmail
オプション ($ZodEmailParams) |
型 | デフォルト値 | 説明 |
|---|---|---|---|
pattern |
RegExp |
z.regexes.email |
カスタム正規表現(z.regexes.email, z.regexes.html5Email, z.regexes.rfc5322Email, z.regexes.unicodeEmail, z.regexes.browserEmail)。 |
error |
string | $ZodErrorMap |
undefined |
カスタムエラーメッセージまたはコールバック。 |
import { z } from "zod";
const CorpEmail = z.email({ pattern: z.regexes.html5Email });
functionz.uuid#
RFC 9562 / RFC 4122 準拠の UUID 文字列、および分散識別子フォーマット(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
| コンストラクタ | オプション | 説明 |
|---|---|---|
z.uuid(params?) |
{ version?: "v1" | "v2" | "v3" | "v4" | "v5" | "v6" | "v7" | "v8" } |
厳密な RFC 9562 UUID を検証します(オプションで特定バージョンに制限可能)。 |
z.uuidv4() / z.uuidv6() / z.uuidv7() |
string | { error? } |
バージョンを "v4"、"v6"、"v7" に固定した専用コンストラクタ。 |
z.guid(params?) |
string | { error? } |
バージョン・バリアントビットを制限しない汎用的な 8-4-4-4-12 形式の 16 進文字列。 |
z.nanoid(params?) |
{ length?: number, error? } |
URL セーフな NanoID 文字列を検証します(デフォルト 21 文字、length で変更可能)。 |
z.cuid2() / z.ulid() / z.xid() / z.ksuid() |
string | { error? } |
衝突耐性・ソート可能性を備えた各種 ID フォーマットを検証します。 |
import { z } from "zod";
const EventId = z.uuidv7();
const ShortId = z.nanoid({ length: 12 });
functionz.url#
WHATWG URL パーサーを用いて URL を検証し、オプションで protocol や hostname の正規表現ガードおよび .href 正規化を実行します。z.httpUrl() は Web 用に protocol: /^https?$/i と hostname: z.regexes.domain を事前設定します。
function z.url(params?: string | core.$ZodURLParams): ZodURL
function z.httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL
オプション ($ZodURLParams) |
型 | デフォルト値 | 説明 |
|---|---|---|---|
protocol |
RegExp |
undefined |
末尾コロンを除いた url.protocol に対する正規表現(例: /^https$/)。 |
hostname |
RegExp |
undefined |
url.hostname に対する正規表現(例: /\.example\.com$/)。 |
normalize |
boolean |
false |
true の場合、出力文字列を new URL(input).href に正規化します。 |
import { z } from "zod";
const WebhookUrl = z.url({
protocol: /^https$/,
hostname: z.regexes.domain,
normalize: true,
});
functionz.jwt#
JSON Web Token(3 パート base64url 構造および JSON ヘッダーの alg クレーム)、およびエンコーディング・暗号学的ハッシュ・電話番号・金融識別子を検証します。
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
| コンストラクタ | オプション / 引数 | 検証の挙動 |
|---|---|---|
z.jwt(params?) |
{ alg?: JWTAlgorithm, error? } |
3 セグメントの base64url とヘッダー JSON を検証し、typ: "JWT"(存在時)と alg を確認します。 |
z.base64() / z.base64url() |
string | { error? } |
大容量文字列でも正規表現スタックオーバーフローを起こさない線形時間 O(n) 検証。 |
z.hash(alg, params?) |
alg: "md5" | "sha1" | "sha256" | "sha384" | "sha512", enc?: "hex" | "base64" | "base64url" |
アルゴリズムとエンコード方式に応じた正確なダイジェスト長・文字種を検証します。 |
z.e164() / z.creditCard() / z.iban() |
string | { error? } |
E.164 国際電話番号、Luhn チェックサム付きクレジットカード番号、ISO 7064 Mod 97-10 IBAN を検証します。 |
import { z } from "zod";
const BearerJwt = z.jwt({ alg: "RS256" });
const CommitSha256 = z.hash("sha256", { enc: "hex" });
functionz.ipv4 & z.ipv6#
ネットワークアドレス、CIDR ブロック、MAC アドレス、DNS ホスト名を検証します。
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>
| コンストラクタ | オプション | 説明 |
|---|---|---|
z.ipv4() / z.ipv6() |
string | { error? } |
ドット区切り IPv4 または RFC 4291 IPv6 アドレスを厳密に検証します。 |
z.cidrv4() / z.cidrv6() |
string | { error? } |
IPv4 CIDR(/0../32)または IPv6 CIDR(/0../128)サブネット表記を検証します。 |
z.mac(params?) |
{ delimiter?: string, error? } |
6 オクテット IEEE 802 MAC アドレスを検証します(delimiter で区切り文字を指定可能)。 |
z.stringFormat(name, fnOrRegex, params?) |
フォーマット名 + 検証関数/正規表現 | ユーザー定義の ZodCustomStringFormat<Format> を作成します。 |
import { z } from "zod";
const Subnet = z.union([z.cidrv4(), z.cidrv6()]);
const MacColon = z.mac({ delimiter: ":" });
namespace z.iso#
z.iso 名前空間は、厳密な ISO 8601 日付・時刻・日時・期間文字列スキーマ(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;
}
| コンストラクタ | オプション (params) |
デフォルトの検証挙動 |
|---|---|---|
z.iso.datetime(params?) |
{ offset?: boolean, local?: boolean, precision?: number | null } |
デフォルトでは末尾 Z(UTC)を要求。offset: true で ±HH:MM を許可、local: true でタイムゾーンなしローカル日時を許可。precision(TimePrecision)で小数秒桁数を固定可能。 |
z.iso.date(params?) |
string | { error? } |
うるう年および各月の日数を考慮して YYYY-MM-DD 日付文字列を検証します。 |
z.iso.time(params?) |
{ precision?: number | null, error? } |
タイムゾーンオフセットを含まない 24 時間表記 HH:MM:SS[.sss] を検証します。 |
z.iso.duration(params?) |
string | { error? } |
ISO 8601 期間文字列(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#
トップ型・ボトム型・空値・シンボル・Web File 用の特殊スキーマコンストラクタ群です。
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
| コンストラクタ | 推論される型 | ランタイム検証内容 |
|---|---|---|
z.any() / z.unknown() |
any / unknown |
ランタイム検査を行わず、あらゆる入力値を通過させます。 |
z.never(params?) |
never |
常に invalid_type(expected: "never")で失敗します。 |
z.void(params?) / z.undefined(params?) |
void / undefined |
input === undefined を検証します。 |
z.null(params?) |
null |
input === null を検証します。 |
z.nan(params?) |
number |
Number.isNaN(input) を検証します。 |
z.symbol(params?) |
symbol |
typeof input === "symbol" を検証します。 |
z.file(params?) |
File |
input instanceof File を検証し、.min(bytes)・.max(bytes)・.mime(types) メソッドを提供します。 |
import { z } from "zod";
const AvatarUpload = z
.file()
.min(1024)
.max(5 * 1024 * 1024)
.mime(["image/png", "image/webp"]);