ZO

zod-patterns

A collection of Zod validation patterns and DTO helpers for MX Space projects.

Install

mkdir -p .claude/skills/zod-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3157" && unzip -o skill.zip -d .claude/skills/zod-patterns && rm skill.zip

Installs to .claude/skills/zod-patterns

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.

MX Space project Zod schema patterns. Apply when creating DTOs, validation schemas, or handling request validation.
115 chars✓ has a “when” trigger
Intermediate

Key capabilities

  • Define Zod schemas for DTOs
  • Apply project-wide custom validators
  • Perform schema composition with extend
  • Implement conditional validation with refine
  • Infer TypeScript types from schemas

How it works

It provides a collection of pre-configured Zod validators and helpers located in the project's common directory to standardize data validation across NestJS endpoints.

Inputs & outputs

You give it
Raw request data object
You get back
Validated and typed DTO instance

When to use zod-patterns

  • Validate API request bodies
  • Define DTOs for NestJS endpoints
  • Create partial schemas for update operations
  • Apply project-wide custom string or number constraints

About this skill

Zod Schema Patterns

Basic Pattern

import { z } from 'zod'
import { createZodDto } from 'nestjs-zod'

// Define Schema
export const MySchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
})

// Create DTO class
export class MyDto extends createZodDto(MySchema) {}

// Partial DTO for updates
export class PartialMyDto extends createZodDto(MySchema.partial()) {}

Project Custom Validators

Location: apps/core/src/common/zod/

import {
  // From primitives.ts:
  zNonEmptyString,       // Non-empty string (z.string().min(1))
  zCoerceInt,            // Coerced integer
  zCoercePositiveInt,    // Coerced positive integer
  zCoerceBoolean,        // Coerced boolean (handles 'true'/'1'/1/etc.)
  zCoerceDate,           // Coerced date
  zOptionalDate,         // Optional date (null/empty → undefined)
  zOptionalBoolean,      // Optional coerced boolean
  zEmptyStringToNull,    // Empty string → null, else string
  zNilOrString,          // string | null | undefined
  zHexColor,             // Hex color (#fff or #ffffff)
  zAllowedUrl,           // HTTP or HTTPS URL
  zStrictUrl,            // Strict URL validation
  zHttpsUrl,             // HTTPS-only URL
  zPaginationPage,       // Coerced int, min 1, default 1
  zPaginationSize,       // Coerced int, min 1, max 50, default 20
  zSortOrder,            // 1 | -1 | undefined (accepts 'asc'/'desc')
  zArrayUnique,          // Unique array elements (generic)
  zUniqueStringArray,    // Unique non-empty string array

  // From custom.ts:
  zBooleanOrString,      // boolean | string union
  zTransformEmptyNull,   // Empty string → null (generic wrapper)
  zTransformBoolean,     // Transform to optional boolean
  zPinDate,              // Pin date (Date | null | undefined, true=now, false=null)
  zSlug,                 // Slug string (trimmed)
  zEmail,                // Email with custom message
  zUrl,                  // URL with custom message
  zMaxLengthString,      // Max length string factory
  zRefTypeTransform,     // Content ref type ('post'→'Post', etc.)
  zPrefer,               // 'lexical' enum optional
  zLang,                 // 2-char language code

  // From shared/id/entity-id.ts:
  zEntityId,             // Snowflake entity ID string validation
  zEntityIdOrInt,        // Entity ID or positive integer union
} from '~/common/zod'

Entity ID Validation

import { zEntityId } from '~/common/zod'

const Schema = z.object({
  id: zEntityId,                    // Snowflake ID string
  categoryId: zEntityId,            // Foreign key reference
  relatedIds: z.array(zEntityId),   // Array of entity IDs
})

// For DTOs used in path params:
import { EntityIdDto } from '~/shared/dto/id.dto'
// EntityIdDto = { id: zEntityId }

Extending Base Schemas

// Compose schemas using .extend()
const PostSchema = z.object({
  title: zNonEmptyString,
  slug: zSlug,
  categoryId: zEntityId,
  tags: z.array(z.string()).optional(),
  contentFormat: z.enum(['markdown', 'lexical']),
})

Common Patterns

Optional Fields with Defaults

z.boolean().default(true).optional()
z.number().default(0).optional()
z.array(z.string()).default([]).optional()

Preprocessing

// Empty string to null
z.preprocess(
  (val) => (val === '' ? null : val),
  z.string().nullable()
).optional()

// String to number
z.preprocess(
  (val) => (typeof val === 'string' ? parseInt(val, 10) : val),
  z.number()
)

Union Types

z.union([z.string(), z.number()])
z.enum(['draft', 'published', 'archived'])

Array Validation

// Basic array
z.array(z.string())

// Length constraints
z.array(z.string()).min(1).max(10)

// Unique elements
zArrayUnique(z.string())

Nested Objects

const AddressSchema = z.object({
  street: z.string(),
  city: z.string(),
})

const UserSchema = z.object({
  name: z.string(),
  address: AddressSchema.optional(),
  addresses: z.array(AddressSchema).optional(),
})

Conditional Validation

// refine for custom validation
z.object({
  password: z.string(),
  confirmPassword: z.string(),
}).refine(
  (data) => data.password === data.confirmPassword,
  { message: 'Passwords must match' }
)

Type Inference

// Infer type from Schema
type MyType = z.infer<typeof MySchema>

// Use in Service
async create(data: z.infer<typeof MySchema>) {
  return this.repository.create(data)
}

When not to use it

  • When standard Zod primitives suffice without project-specific helpers

Prerequisites

nestjs-zod

Limitations

  • Requires manual import of specific validators from the common directory

How it compares

Unlike manual Zod schema definitions, this provides a centralized library of project-specific validators and DTO factories to ensure consistency.

Compared to similar skills

zod-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
zod-patterns (this skill)13moNo flagsIntermediate
effect-ts-expert76moReviewAdvanced
node01moNo flagsIntermediate
supabase-developer957moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

effect-ts-expert

ojowwalker77

This skill should be used when the user is working with Effect-TS, asks to "write Effect code", "use Effect", "functional TypeScript", "handle errors with Effect", "dependency injection Effect", "Effect Layer", or needs expert-level guidance on Effect-TS patterns, error handling, concurrency, and best practices.

744

node

dannybrown37

Invoke when the user is writing or debugging TypeScript or JavaScript code, working with Node.js tooling, or asking about ESLint/Prettier configuration.

00

supabase-developer

daffy0208

Build full-stack applications with Supabase (PostgreSQL, Auth, Storage, Real-time, Edge Functions). Use when implementing authentication, database design with RLS, file storage, real-time features, or serverless functions.

95185

turborepo

vercel

Turborepo monorepo build system guidance. Triggers on: turbo.json, task pipelines, dependsOn, caching, remote cache, the "turbo" CLI, --filter, --affected, CI optimization, environment variables, internal packages, monorepo structure/best practices, and boundaries. Use when user: configures tasks/workflows/pipelines, creates packages, sets up monorepo, shares code between apps, runs changed/affected packages, debugs cache, or has apps/packages directories.

61191

telegram-mini-app

davila7

Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.

62163

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

Search skills

Search the agent skills registry