jpskill.com
🛠️ 開発・MCP コミュニティ

zod-validation-patterns

This skill provides comprehensive patterns for using Zod validation library in TypeScript applications. It ensures input validation is done correctly, securely, and consistently across the codebase.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o zod-validation-patterns.zip https://jpskill.com/download/17478.zip && unzip -o zod-validation-patterns.zip && rm zod-validation-patterns.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17478.zip -OutFile "$d\zod-validation-patterns.zip"; Expand-Archive "$d\zod-validation-patterns.zip" -DestinationPath $d -Force; ri "$d\zod-validation-patterns.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して zod-validation-patterns.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → zod-validation-patterns フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
2

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Zod Validation Patterns Skill

このスキルは以下の場合に使用します: Quetrex でのユーザー入力検証、API リクエスト検証、フォームデータ検証、またはデータ変換を行う場合。

目的

このスキルは、TypeScript アプリケーションで Zod 検証ライブラリを使用するための包括的なパターンを提供します。これにより、入力検証がコードベース全体で正しく、安全に、一貫して行われるようになります。

カバー範囲

  1. スキーマパターン - すべての Zod スキーマ型に関する完全なガイド

    • プリミティブ (string, number, boolean, date)
    • コレクション (array, object, map, set, record)
    • 高度な型 (union, intersection, discriminated unions)
    • Optional/nullable パターン
    • Branded types と再帰的スキーマ
  2. エラー処理 - 堅牢なエラー管理

    • カスタムエラーメッセージ
    • 国際化 (i18n)
    • UI 表示のためのエラーフォーマット
    • 安全な解析パターン
    • エラー回復戦略
  3. Refinements - カスタム検証ロジック

    • 基本的な refinements と chained refinements
    • クロスフィールド検証
    • 条件付き検証
    • ビジネスロジック検証
    • ファイルアップロード検証
  4. Transforms - データ変換と正規化

    • 型強制
    • データクレンジングと正規化
    • 算出フィールド
    • 前処理パターン
  5. Async Validation - 非同期検証パターン

    • データベースの一意性チェック
    • API 検証
    • 並行非同期検証
    • エラー処理とタイムアウト
  6. Type Inference - TypeScript 型抽出

    • z.infer パターン
    • 入力 vs 出力型
    • ジェネリックスキーマ型
    • Discriminated union の推論
  7. API Integration - Next.js 統合パターン

    • API ルート検証
    • Server Actions 検証
    • フォームデータとファイルアップロード
    • エラーレスポンスフォーマット
  8. Common Schemas - 再利用可能なスキーマライブラリ

    • Email, password, phone 検証
    • URL, UUID, date スキーマ
    • Address, credit card 検証
    • Username, slug, color スキーマ

クイックスタート

基本的な使い方

import { z } from 'zod'

// スキーマを定義
const userSchema = z.object({
  email: z.string().email(),
  age: z.number().int().positive(),
  role: z.enum(['admin', 'user'])
})

// データを解析 (エラー時に例外をスロー)
const user = userSchema.parse(data)

// 安全な解析 (結果オブジェクトを返す)
const result = userSchema.safeParse(data)
if (result.success) {
  console.log(result.data)
} else {
  console.error(result.error)
}

型推論

// スキーマから TypeScript 型を抽出
type User = z.infer<typeof userSchema>
// { email: string; age: number; role: 'admin' | 'user' }

API ルートの例

// src/app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

const createUserSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8)
})

export async function POST(request: NextRequest) {
  const body = await request.json()

  const result = createUserSchema.safeParse(body)
  if (!result.success) {
    return NextResponse.json(
      { error: 'Validation failed', details: result.error.format() },
      { status: 400 }
    )
  }

  // 検証済みのデータを処理
  const { email, password } = result.data
  // ...
}

このスキルを使用するタイミング

以下の場合は使用してください:

  • API リクエスト検証 - API ルートへのすべての受信データ
  • フォーム送信検証 - クライアント側とサーバー側
  • データベース入力検証 - 挿入/更新前
  • 構成検証 - 環境変数、構成ファイル
  • ファイルアップロード検証 - サイズ、タイプ、コンテンツ検証
  • 外部 API レスポンス - サードパーティデータの検証

以下の場合は使用しないでください:

  • 単純な型チェック - 検証が必要ない場合は TypeScript 型を使用
  • ランタイムパフォーマンスが重要なパス - 検証にはオーバーヘッドがあります
  • すでに検証済みのデータ - 信頼できる内部データを再検証しないでください

ベストプラクティス

  1. 境界で検証 - API ルート、Server Actions、外部データソース
  2. 安全な解析を使用 - より良いエラー処理のために parse() よりも safeParse() を優先
  3. 明確なエラーメッセージを提供する - ユーザー向けの検証のためにメッセージをカスタマイズ
  4. 共通スキーマを再利用 - common-schemas.md からスキーマを使用
  5. 型推論 - TypeScript 型には常に z.infer<typeof schema> を使用
  6. エッジケースをテスト - 検証ロジックのテストを作成
  7. 複雑なスキーマをドキュメント化 - ビジネスルールに関する JSDoc コメントを追加

一般的なパターン

1. デフォルト値を持つオプションフィールド

const configSchema = z.object({
  timeout: z.number().int().positive().default(30),
  retries: z.number().int().min(0).default(3),
  debug: z.boolean().optional()
})

2. 条件付き必須フィールド

const addressSchema = z.object({
  country: z.string(),
  state: z.string().optional()
}).refine(
  data => data.country === 'US' ? !!data.state : true,
  { message: 'State is required for US addresses', path: ['state'] }
)

3. 変換と検証

const emailSchema = z.string()
  .trim()
  .toLowerCase()
  .email()

4. Discriminated Unions

const eventSchema = z.discriminatedUnion('type', [
  z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),
  z.object({ type: z.literal('keypress'), key: z.string() })
])

5. 非同期データベースチェック

const usernameSchema = z.string()
  .min(3)
  .max(20)
  .regex(/^[a-zA-Z0-9_-]+$/)
  .refine(async (username) => {
    const existing = await db.user.findUnique({ where: { username } })
    return !existing
  }, { message: 'Username already taken' })

Quetrex との統合

TypeScript Strict Mode への準拠

すべてのスキーマは TypeScript strict mode で動作する必要があります:

  • any 型は使用しない
  • @ts-ignore コメントは使用しない
  • 明示的な型推論を使用
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Zod Validation Patterns Skill

Use this skill when: Working with user input validation, API request validation, form data validation, or data transformation in Quetrex.

Purpose

This skill provides comprehensive patterns for using Zod validation library in TypeScript applications. It ensures input validation is done correctly, securely, and consistently across the codebase.

What's Covered

  1. Schema Patterns - Complete guide to all Zod schema types

    • Primitives (string, number, boolean, date)
    • Collections (array, object, map, set, record)
    • Advanced types (union, intersection, discriminated unions)
    • Optional/nullable patterns
    • Branded types and recursive schemas
  2. Error Handling - Robust error management

    • Custom error messages
    • Internationalization (i18n)
    • Error formatting for UI display
    • Safe parsing patterns
    • Error recovery strategies
  3. Refinements - Custom validation logic

    • Basic and chained refinements
    • Cross-field validation
    • Conditional validation
    • Business logic validation
    • File upload validation
  4. Transforms - Data transformation and normalization

    • Type coercion
    • Data cleaning and normalization
    • Computed fields
    • Preprocessing patterns
  5. Async Validation - Asynchronous validation patterns

    • Database uniqueness checks
    • API validations
    • Concurrent async validations
    • Error handling and timeouts
  6. Type Inference - TypeScript type extraction

    • z.infer patterns
    • Input vs output types
    • Generic schema types
    • Discriminated union inference
  7. API Integration - Next.js integration patterns

    • API routes validation
    • Server Actions validation
    • Form data and file uploads
    • Error response formatting
  8. Common Schemas - Reusable schema library

    • Email, password, phone validation
    • URL, UUID, date schemas
    • Address, credit card validation
    • Username, slug, color schemas

Quick Start

Basic Usage

import { z } from 'zod'

// Define schema
const userSchema = z.object({
  email: z.string().email(),
  age: z.number().int().positive(),
  role: z.enum(['admin', 'user'])
})

// Parse data (throws on error)
const user = userSchema.parse(data)

// Safe parse (returns result object)
const result = userSchema.safeParse(data)
if (result.success) {
  console.log(result.data)
} else {
  console.error(result.error)
}

Type Inference

// Extract TypeScript type from schema
type User = z.infer<typeof userSchema>
// { email: string; age: number; role: 'admin' | 'user' }

API Route Example

// src/app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

const createUserSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8)
})

export async function POST(request: NextRequest) {
  const body = await request.json()

  const result = createUserSchema.safeParse(body)
  if (!result.success) {
    return NextResponse.json(
      { error: 'Validation failed', details: result.error.format() },
      { status: 400 }
    )
  }

  // Process validated data
  const { email, password } = result.data
  // ...
}

When to Use This Skill

DO Use for:

  • API request validation - All incoming data to API routes
  • Form submission validation - Client and server-side
  • Database input validation - Before inserting/updating
  • Configuration validation - Environment variables, config files
  • File upload validation - Size, type, content validation
  • External API responses - Validate third-party data

DON'T Use for:

  • Simple type checks - Use TypeScript types when validation isn't needed
  • Runtime performance-critical paths - Validation has overhead
  • Already validated data - Don't re-validate trusted internal data

Best Practices

  1. Validate at boundaries - API routes, Server Actions, external data sources
  2. Use safe parsing - Prefer safeParse() over parse() for better error handling
  3. Provide clear error messages - Customize messages for user-facing validation
  4. Reuse common schemas - Use schemas from common-schemas.md
  5. Type inference - Always use z.infer<typeof schema> for TypeScript types
  6. Test edge cases - Write tests for validation logic
  7. Document complex schemas - Add JSDoc comments for business rules

Common Patterns

1. Optional Fields with Defaults

const configSchema = z.object({
  timeout: z.number().int().positive().default(30),
  retries: z.number().int().min(0).default(3),
  debug: z.boolean().optional()
})

2. Conditional Required Fields

const addressSchema = z.object({
  country: z.string(),
  state: z.string().optional()
}).refine(
  data => data.country === 'US' ? !!data.state : true,
  { message: 'State is required for US addresses', path: ['state'] }
)

3. Transform and Validate

const emailSchema = z.string()
  .trim()
  .toLowerCase()
  .email()

4. Discriminated Unions

const eventSchema = z.discriminatedUnion('type', [
  z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),
  z.object({ type: z.literal('keypress'), key: z.string() })
])

5. Async Database Check

const usernameSchema = z.string()
  .min(3)
  .max(20)
  .regex(/^[a-zA-Z0-9_-]+$/)
  .refine(async (username) => {
    const existing = await db.user.findUnique({ where: { username } })
    return !existing
  }, { message: 'Username already taken' })

Integration with Quetrex

TypeScript Strict Mode Compliance

All schemas must work with TypeScript strict mode:

  • No any types
  • No @ts-ignore comments
  • Explicit type inference with z.infer

Testing Requirements

Validation logic requires comprehensive tests:

  • Happy path - Valid data passes
  • Edge cases - Boundary values, empty strings, null/undefined
  • Error cases - Invalid data produces expected errors
  • Custom validations - All refinements and transforms tested

Server Actions Pattern

'use server'

import { z } from 'zod'

const createProjectSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().optional()
})

export async function createProject(formData: FormData) {
  const result = createProjectSchema.safeParse({
    name: formData.get('name'),
    description: formData.get('description')
  })

  if (!result.success) {
    return { error: result.error.format() }
  }

  // Process validated data
  return { success: true, data: result.data }
}

Resources

Navigation

Start with:

  1. Schema Patterns - Learn all schema types
  2. Common Schemas - Use ready-made schemas
  3. API Integration - Integrate with Next.js

Then explore:


Last updated: 2025-11-23 | Zod v4.1.12

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。