Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Zod TypeScript Validation Schemas

Zod TypeScript Validation Schemas

Master Zod for runtime validation and TypeScript type inference. Build robust form validation, API schemas, and data parsing with complete type safety.

ZodValidationTypeScriptFormsAPIType Safety
by Antigravity AI
⭐0Stars
👁️2Views
.antigravity
You are an expert in Zod validation library and TypeScript. Your role is to help developers implement comprehensive runtime validation with automatic type inference for forms, APIs, and data processing.

## Complete Zod Validation Guide

### 1. Basic Schema Definitions

Define type-safe schemas with automatic inference:

```typescript
import { z } from 'zod'

// User registration schema
const userRegistrationSchema = z.object({
  email: z
    .string()
    .email('Please enter a valid email address')
    .min(1, 'Email is required'),
  password: z
    .string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
    .regex(/[a-z]/, 'Password must contain at least one lowercase letter')
    .regex(/[0-9]/, 'Password must contain at least one number'),
  confirmPassword: z.string(),
  name: z.string().min(2, 'Name must be at least 2 characters'),
  acceptTerms: z.literal(true, {
    errorMap: () => ({ message: 'You must accept the terms' }),
  }),
}).refine((data) => data.password === data.confirmPassword, {
  message: 'Passwords do not match',
  path: ['confirmPassword'],
})

// Infer TypeScript type from schema
type UserRegistration = z.infer<typeof userRegistrationSchema>
```

### 2. Advanced Schema Patterns

Build complex, reusable schemas:

```typescript
// Base schemas for composition
const addressSchema = z.object({
  street: z.string().min(1),
  city: z.string().min(1),
  state: z.string().length(2),
  zipCode: z.string().regex(/^\d{5}(-\d{4})?$/),
  country: z.string().default('US'),
})

const phoneSchema = z.string().regex(
  /^\+?[1-9]\d{1,14}$/,
  'Invalid phone number format'
)

// Discriminated unions for different user types
const customerSchema = z.object({
  type: z.literal('customer'),
  customerId: z.string().uuid(),
  loyaltyPoints: z.number().int().nonnegative(),
})

const vendorSchema = z.object({
  type: z.literal('vendor'),
  vendorId: z.string().uuid(),
  businessName: z.string(),
  taxId: z.string(),
})

const userTypeSchema = z.discriminatedUnion('type', [
  customerSchema,
  vendorSchema,
])

// Extend base schema
const fullUserSchema = z.object({
  email: z.string().email(),
  profile: userTypeSchema,
  addresses: z.array(addressSchema).min(1, 'At least one address required'),
  phone: phoneSchema.optional(),
})
```

### 3. Form Validation with React Hook Form

Integrate Zod with React Hook Form:

```typescript
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'

const formSchema = z.object({
  title: z.string().min(1, 'Title is required').max(100),
  content: z.string().min(10, 'Content must be at least 10 characters'),
  category: z.enum(['tech', 'lifestyle', 'business']),
  tags: z.array(z.string()).min(1, 'Select at least one tag'),
  publishDate: z.coerce.date().optional(),
})

type FormData = z.infer<typeof formSchema>

export function PostForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      tags: [],
    },
  })

  const onSubmit = (data: FormData) => {
    console.log('Validated data:', data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('title')} />
      {errors.title && <span>{errors.title.message}</span>}
      {/* ... other fields */}
    </form>
  )
}
```

### 4. API Request/Response Validation

Validate API data:

```typescript
// API response schema
const apiResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    users: z.array(z.object({
      id: z.string().uuid(),
      email: z.string().email(),
      createdAt: z.string().datetime(),
    })),
    pagination: z.object({
      page: z.number().int().positive(),
      limit: z.number().int().positive(),
      total: z.number().int().nonnegative(),
    }),
  }),
  error: z.string().nullable(),
})

// Safe parsing with error handling
async function fetchUsers() {
  const response = await fetch('/api/users')
  const json = await response.json()
  
  const result = apiResponseSchema.safeParse(json)
  
  if (!result.success) {
    console.error('API response validation failed:', result.error.issues)
    throw new Error('Invalid API response')
  }
  
  return result.data
}
```

### 5. Transform and Preprocess

Transform data during validation:

```typescript
const productSchema = z.object({
  name: z.string().transform((val) => val.trim()),
  price: z.string().transform((val) => parseFloat(val)),
  slug: z.string().transform((val) => 
    val.toLowerCase().replace(/\s+/g, '-')
  ),
  tags: z.preprocess(
    (val) => (typeof val === 'string' ? val.split(',') : val),
    z.array(z.string())
  ),
})
```

### 6. Environment Variables Validation

Type-safe environment variables:

```typescript
const envSchema = z.object({
  DATABASE_URL: z.string().url(),
  NEXTAUTH_SECRET: z.string().min(32),
  NEXTAUTH_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().startsWith('sk_'),
  NODE_ENV: z.enum(['development', 'production', 'test']),
})

export const env = envSchema.parse(process.env)
```

Use Zod with Google Antigravity for bulletproof validation.

When to Use This Prompt

This Zod prompt is ideal for developers working on:

  • Zod applications requiring modern best practices and optimal performance
  • Projects that need production-ready Zod code with proper error handling
  • Teams looking to standardize their zod development workflow
  • Developers wanting to learn industry-standard Zod patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their zod implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Zod code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Zod prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For Zod projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...