DA

data-validation-schemas

Provides patterns for robust data validation using Zod, Yup, Joi, and Pydantic.

Install

mkdir -p .claude/skills/data-validation-schemas && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/13366" && unzip -o skill.zip -d .claude/skills/data-validation-schemas && rm skill.zip

Installs to .claude/skills/data-validation-schemas

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Data validation and schema design mastery. Zod, Yup, Joi, Valibot, and Pydantic schema design, runtime type checking, API boundary validation, form validation patterns, DTO design, schema composition, error message formatting, schema evolution strategies, and coercion rules. Use when validating user input, API payloads, environment config, or any data crossing a trust boundary.
380 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • →Design schemas for API request bodies and query strings
  • →Validate environment variables at application startup
  • →Create schemas for external API responses
  • →Implement form validation patterns
  • →Format validation errors into user-friendly messages
  • →Compose and reuse schemas for different data structures

How it works

The skill defines schemas using Zod to specify data shapes and constraints, then applies these schemas to validate data at trust boundaries.

Inputs & outputs

You give it
Raw user input, API payloads, or environment variables
You get back
Validated and coerced data, or formatted validation errors

When to use data-validation-schemas

  • →Validating API payloads
  • →Creating form validation schemas
  • →Securing application data inputs

About this skill

Data Validation & Schemas — Trust No Input

Mandatory Pre-Flight Context Inspection

Before reading, generating, or refactoring code in the data-validation-schemas domain, inspect these 5 critical parameters:

  1. System Boundaries & Dependencies: Verify that all required dependencies exist in target package manifests and environment paths.
  2. Runtime Context & Platform Invariants: Confirm target platform constraints (Node.js, Browser, Mobile OS, Edge runtime) before applying APIs.
  3. Execution Guardrails: Identify potential side-effects, state mutations, and unhandled asynchronous exceptions.
  4. Validation & Type Contracts: Validate input data schemas and strict type constraints across all module interfaces.
  5. Observability & Proof of Execution: Ensure execution produces tangible verification signals (terminal output, tests, metrics).

Activation Boundaries

  • Activate when: Use when designing schemas, querying, indexing, optimizing, and securing data validation schemas databases and data models.
  • DO NOT activate when: The task falls outside the data-validation-schemas domain or is managed by a different dedicated specialist agent.

🔁 Multi-Pass Execution Protocol

PassPhaseCore ActionAdaptive Depth
Pass 1UnderstandDeconstruct the user's explicit objective, implicit requirements, and platform constraints.Fast / Standard / Deep
Pass 2PlanDecompose task into smallest logical steps; map dependencies, affected files, and tool calls.Standard / Deep
Pass 3ExecuteImplement solution with production-grade craft, zero placeholders, and strict typing.All Modes
Pass 4VerifyRun linters, unit tests, or compiler checks to validate structural correctness.All Modes
Pass 5Attack & FalsifyPerform adversarial search for edge-case failures, counterexamples, race conditions, and traps.Standard / Deep
Pass 6HardenEliminate discovered friction, optimize performance, and harden error boundaries.Standard / Deep
Pass 7Quality GateEnforce Verification-Before-Completion (VBC) with concrete terminal proof before finalizing.All Modes

🛠️ Technical Architecture & Reference Recipes

Hallucination Traps (Read First)

  • ❌ Using z.any() or z.unknown() as a lazy escape hatch -> ✅ Always define the actual shape; any defeats the purpose of validation
  • ❌ Validating on the client but not on the server -> ✅ Server validation is NOT optional — client validation is UX, server validation is security
  • ❌ Throwing raw Zod errors to the client -> ✅ Format errors into user-friendly messages with .flatten() or .format()

The Golden Rule

Every trust boundary gets a schema.
No exceptions. No shortcuts. No "I'll add validation later."

Trust Boundaries:
  ✅ API request bodies         (user → server)
  ✅ URL params / query strings  (user → server)
  ✅ Environment variables       (env → app)
  ✅ External API responses      (3rd party → app)
  ✅ Database query results      (DB → app, if untyped)
  ✅ File uploads                (user → server)
  ✅ WebSocket messages          (client → server)
  ✅ Form inputs                 (user → UI)

Zod (Recommended — TypeScript)

Basic Schemas

import { z } from 'zod';

// Primitives with constraints
const Email = z.string().email().toLowerCase().trim();
const Age = z.number().int().min(0).max(150);
const Username = z
  .string()
  .min(3)
  .max(30)
  .regex(/^[a-zA-Z0-9_]+$/);
const URL = z.string().url().startsWith('https://');

// Object schema
const CreateUserSchema = z.object({
  name: z.string().min(2).max(100),
  email: Email,
  age: Age.optional(),
  role: z.enum(['admin', 'editor', 'viewer']).default('viewer'),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

// ✅ Infer TypeScript types from schemas (single source of truth)
type CreateUserInput = z.infer<typeof CreateUserSchema>;
// → { name: string; email: string; age?: number; role: "admin" | "editor" | "viewer"; ... }

Composition & Reuse

// ✅ Base schema + extend for variants
const BaseUserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
});

const CreateUserSchema = BaseUserSchema.extend({
  password: z.string().min(8),
  confirmPassword: z.string(),
}).refine(data => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ['confirmPassword'],
});

const UpdateUserSchema = BaseUserSchema.partial(); // all fields optional

// ✅ Pick / Omit
const LoginSchema = BaseUserSchema.pick({ email: true }).extend({
  password: z.string(),
});

// ✅ Merge two schemas
const FullProfileSchema = BaseUserSchema.merge(AddressSchema);

API Boundary Validation

// ✅ Server-side: validate at the boundary, type-safe downstream
import { z } from 'zod';

// Define once, use everywhere
const QuerySchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  sort: z.enum(['created', 'updated', 'name']).default('created'),
  order: z.enum(['asc', 'desc']).default('desc'),
  search: z.string().max(200).optional(),
});

// Express middleware
function validate<T extends z.ZodType>(schema: T) {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      return res.status(400).json({
        error: 'Validation failed',
        issues: result.error.flatten().fieldErrors,
      });
    }
    req.body = result.data; // ✅ Validated + coerced data replaces raw body
    next();
  };
}

app.post('/api/users', validate(CreateUserSchema), async (req, res) => {
  // req.body is now fully typed and validated
  const user = await createUser(req.body);
  res.status(201).json(user);
});

// ❌ BAD: Validating inside the handler
// ✅ GOOD: Validation as middleware — keeps handlers clean

Error Formatting

// ✅ User-friendly error messages
const result = CreateUserSchema.safeParse(rawInput);

if (!result.success) {
  // .flatten() — flat structure for simple forms
  const flat = result.error.flatten();
  // { fieldErrors: { email: ["Invalid email"], name: ["Too short"] } }

  // .format() — nested structure matching schema shape
  const formatted = result.error.format();
  // { email: { _errors: ["Invalid email"] }, name: { _errors: ["Too short"] } }

  // Custom error map (global)
  z.setErrorMap((issue, ctx) => {
    if (issue.code === z.ZodIssueCode.too_small) {
      return { message: `Must be at least ${issue.minimum} characters` };
    }
    return { message: ctx.defaultError };
  });
}

Environment Validation (Fail Fast)

// ✅ Validate ALL env vars at startup — crash immediately if invalid
const EnvSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url().optional(),
  JWT_SECRET: z.string().min(32, 'JWT_SECRET must be ≥ 32 characters'),
  API_KEY: z.string().min(1),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

export const env = EnvSchema.parse(process.env);

// ❌ TRAP: process.env.DATABASE_URL! ← crashes at RUNTIME, not startup
// ✅ Parse at module load → crash at STARTUP with clear error message

Pydantic (Python)

from pydantic import BaseModel, Field, field_validator, model_validator
from datetime import datetime

class CreateUserRequest(BaseModel):
    name: str = Field(min_length=2, max_length=100)
    email: str = Field(pattern=r"^[\w\.\+\-]+@[\w]+\.[\w\.]+$")
    age: int | None = Field(default=None, ge=0, le=150)
    role: str = Field(default="viewer")

    @field_validator("email")
    @classmethod
    def normalize_email(cls, v: str) -> str:
        return v.lower().strip()

    @field_validator("role")
    @classmethod
    def validate_role(cls, v: str) -> str:
        allowed = {"admin", "editor", "viewer"}
        if v not in allowed:
            raise ValueError(f"Role must be one of: {allowed}")
        return v

# FastAPI uses Pydantic automatically
@app.post("/users")
async def create_user(user: CreateUserRequest):
    # user is already validated and typed
    return await db.create_user(user.model_dump())

Form Validation (React + Zod)

// ✅ React Hook Form + Zod = type-safe forms
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const SignupSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z
    .string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/[A-Z]/, 'Must contain uppercase letter')
    .regex(/[0-9]/, 'Must contain a number'),
  terms: z.literal(true, {
    errorMap: () => ({ message: 'You must accept the terms' }),
  }),
});

type SignupData = z.infer<typeof SignupSchema>;

function SignupForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<SignupData>({
    resolver: zodResolver(SignupSchema),
  });

  return (
    <form onSubmit={handleSubmit(data => signup(data))}>
      <input {...register('email')} />
      {errors.email && <span>{errors.email.message}</span>}

      <input type="password" {...register('password')} />
      {errors.password && <span>{errors.password.message}</span>}

      <label>
        <input type="checkbox" {...register('terms')} />I accept the terms
      </label>
      {errors.terms && <span>{errors.terms.message}</span>}

      <button type="submit">Sign Up</button>
    </form>
  );
}

Schema Anti-Patterns

❌ z.any() / z.unknown() as a lazy escape — defeats the purpose
❌ Validating on client only — server is the security boundary
❌ Different schemas for same entity o

---

*Content truncated.*

When not to use it

  • →The task involves using `z.any()` or `z.unknown()` as a lazy escape hatch
  • →The task only requires client-side validation without server-side validation
  • →The task involves throwing raw Zod errors to the client

Limitations

  • →It does not support using `z.any()` or `z.unknown()` for validation
  • →It requires server-side validation for security, not just client-side validation
  • →It does not throw raw Zod errors to the client

How it compares

This approach enforces data integrity with explicit schemas at every trust boundary, preventing issues that arise from implicit or absent validation.

Compared to similar skills

data-validation-schemas side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
data-validation-schemas (this skill)03moReviewIntermediate
telegram-dev29moReviewIntermediate
codex-code-review19moReviewIntermediate
moai-foundation-quality04moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by Harmitx7

View all by Harmitx7 →

i18n-localization

Harmitx7

Internationalization (i18n) and localization mastery. Abstracting hardcoded strings, managing JSON/YAML translation dictionaries, bidirectional routing (RTL support for Arabic/Hebrew), Pluralization algorithms, date/currency formatting, and SSR locale detection in Next.js/React. Use when preparing a

00

code-review-checklist

Harmitx7

Code review guidelines covering code quality, security, and best practices.

00

performance-profiling

Harmitx7

Performance profiling mastery. Core Web Vitals (LCP, CLS, INP), Lighthouse auditing, JavaScript profiling, React rendering optimization, bundle analysis, memory leak detection, database query profiling (EXPLAIN ANALYZE), load testing, and performance budgets. Use when optimizing performance, debuggi

00

web-accessibility-auditor

Harmitx7

Web Accessibility (a11y) mastery. WCAG 2.2 AA standards, semantic HTML, ARIA attributes, keyboard navigation, focus management, screen reader compatibility, color contrast, and dynamic content announcements. Use when building UI components or auditing frontend code for accessibility compliance.

00

plan-writing

Harmitx7

Technical design and implementation planning mastery. Writing structured execution checklists, dependency mapping, establishing rollback protocols, segmenting monolithic tasks, writing ADRs (Architecture Decision Records), and defining verification criteria. Use when transitioning from ideation to c

00

database-design

Harmitx7

Database design principles and decision-making. Schema design, indexing strategy, ORM selection, serverless databases.

00

You might also like

telegram-dev

2025Emma

Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。

232

codex-code-review

tyrchen

Perform comprehensive code reviews using OpenAI Codex CLI. This skill should be used when users request code reviews, want to analyze diffs/PRs, need security audits, performance analysis, or want automated code quality feedback. Supports reviewing staged changes, specific files, entire directories, or git diffs.

16

moai-foundation-quality

modu-ai

Enterprise code quality orchestrator with TRUST 5 validation, proactive analysis, and automated best practices enforcement

04

add-new-setting-field

tsukumijima

【設定追加時は必ず参照】KonomiTV に新しい設定 (v-switch/v-select など) を追加する際の必須手順。SettingsStore.ts / Settings.ts / config.py / Settings/*.vue への追加が必要

12

verification-loop

tom237ttkk

A comprehensive verification system for Codex work sessions.

00

security-audit

ruvnet

Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement. Use when: authentication implementation, authorization logic, payment processing, user data handling, API endpoint creation, file upload handling, database queries, external API integration. Skip when: read-only operations on public data, internal development tooling, static documentation, styling changes.

337

Search skills

Search the agent skills registry