Create comprehensive type-safe validation schemas with Zod in Google Antigravity for forms APIs and runtime checks
# 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 typesThis Zod prompt is ideal for developers working on:
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.
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.
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.
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.