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 FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 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 Schema Validation Patterns

Zod Schema Validation Patterns

Create comprehensive type-safe validation schemas with Zod in Google Antigravity for forms APIs and runtime checks

ZodValidationTypeScriptFormsAPI
by Antigravity Team
⭐0Stars
.antigravity
# Zod Schema Validation Patterns for Google Antigravity

Runtime validation is essential for maintaining data integrity at system boundaries. This guide establishes patterns for using Zod with Google Antigravity projects, enabling Gemini 3 to generate comprehensive validation schemas that work seamlessly with TypeScript.

## Base Schema Patterns

Define reusable validation schemas:

```typescript
// lib/validations/common.ts
import { z } from "zod";

// Reusable field validators
export const emailSchema = z
  .string()
  .email("Invalid email address")
  .min(5, "Email too short")
  .max(255, "Email too long")
  .toLowerCase()
  .trim();

export const passwordSchema = z
  .string()
  .min(8, "Password must be at least 8 characters")
  .max(100, "Password too long")
  .regex(/[A-Z]/, "Password must contain uppercase letter")
  .regex(/[a-z]/, "Password must contain lowercase letter")
  .regex(/[0-9]/, "Password must contain a number")
  .regex(/[^A-Za-z0-9]/, "Password must contain special character");

export const slugSchema = z
  .string()
  .min(3, "Slug must be at least 3 characters")
  .max(100, "Slug too long")
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Invalid slug format")
  .transform((val) => val.toLowerCase());

export const uuidSchema = z.string().uuid("Invalid UUID format");

export const dateStringSchema = z
  .string()
  .refine((val) => !isNaN(Date.parse(val)), "Invalid date format")
  .transform((val) => new Date(val));

export const paginationSchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  sortBy: z.string().optional(),
  sortOrder: z.enum(["asc", "desc"]).default("desc"),
});

export type PaginationParams = z.infer<typeof paginationSchema>;
```

## Entity Schemas

Create comprehensive entity validation:

```typescript
// lib/validations/user.ts
import { z } from "zod";
import { emailSchema, passwordSchema, uuidSchema } from "./common";

export const userRoleSchema = z.enum(["user", "admin", "moderator"]);

export const userProfileSchema = z.object({
  firstName: z
    .string()
    .min(1, "First name required")
    .max(50, "First name too long")
    .trim(),
  lastName: z
    .string()
    .min(1, "Last name required")
    .max(50, "Last name too long")
    .trim(),
  bio: z.string().max(500, "Bio too long").optional(),
  avatarUrl: z.string().url("Invalid avatar URL").optional(),
  website: z.string().url("Invalid website URL").optional().or(z.literal("")),
  location: z.string().max(100, "Location too long").optional(),
});

export const createUserSchema = z
  .object({
    email: emailSchema,
    password: passwordSchema,
    confirmPassword: z.string(),
    profile: userProfileSchema.partial(),
    role: userRoleSchema.default("user"),
    acceptTerms: z.literal(true, {
      errorMap: () => ({ message: "You must accept the terms" }),
    }),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"],
  });

export const updateUserSchema = userProfileSchema.partial().extend({
  email: emailSchema.optional(),
  currentPassword: z.string().optional(),
  newPassword: passwordSchema.optional(),
}).refine(
  (data) => {
    if (data.newPassword && !data.currentPassword) {
      return false;
    }
    return true;
  },
  {
    message: "Current password required to set new password",
    path: ["currentPassword"],
  }
);

export const userResponseSchema = z.object({
  id: uuidSchema,
  email: emailSchema,
  profile: userProfileSchema,
  role: userRoleSchema,
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime(),
});

export type CreateUserInput = z.infer<typeof createUserSchema>;
export type UpdateUserInput = z.infer<typeof updateUserSchema>;
export type UserResponse = z.infer<typeof userResponseSchema>;
```

## API Validation Middleware

Validate API requests with Zod:

```typescript
// lib/api/validate.ts
import { NextRequest, NextResponse } from "next/server";
import { z, ZodError, ZodSchema } from "zod";

export type ValidationSchemas = {
  body?: ZodSchema;
  query?: ZodSchema;
  params?: ZodSchema;
};

export function validateRequest<T extends ValidationSchemas>(schemas: T) {
  return async (
    req: NextRequest,
    context: { params: Record<string, string> }
  ): Promise<{
    body: T["body"] extends ZodSchema ? z.infer<T["body"]> : undefined;
    query: T["query"] extends ZodSchema ? z.infer<T["query"]> : undefined;
    params: T["params"] extends ZodSchema ? z.infer<T["params"]> : undefined;
    error?: NextResponse;
  }> => {
    try {
      const result: Record<string, unknown> = {};

      if (schemas.body) {
        const json = await req.json().catch(() => ({}));
        result.body = schemas.body.parse(json);
      }

      if (schemas.query) {
        const searchParams = Object.fromEntries(req.nextUrl.searchParams);
        result.query = schemas.query.parse(searchParams);
      }

      if (schemas.params) {
        result.params = schemas.params.parse(context.params);
      }

      return result as ReturnType<typeof validateRequest<T>> extends Promise<infer R> ? R : never;
    } catch (error) {
      if (error instanceof ZodError) {
        return {
          body: undefined,
          query: undefined,
          params: undefined,
          error: NextResponse.json(
            {
              error: "Validation failed",
              details: error.errors.map((e) => ({
                path: e.path.join("."),
                message: e.message,
              })),
            },
            { status: 400 }
          ),
        } as ReturnType<typeof validateRequest<T>> extends Promise<infer R> ? R : never;
      }
      throw error;
    }
  };
}
```

## Best Practices

1. **Composable schemas**: Build complex schemas from smaller pieces
2. **Transform and sanitize**: Clean data during validation
3. **Custom error messages**: Provide user-friendly error text
4. **Discriminated unions**: Use for polymorphic data
5. **Infer types**: Let Zod generate TypeScript types

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...