Comprehensive schema validation with Zod including transformations, refinements, and form integration
# Zod Validation Patterns for Google Antigravity
Build type-safe validation with Zod using Google Antigravity's Gemini 3 engine. This guide covers schema definitions, transformations, custom validators, and integration with forms and APIs.
## Schema Definitions
```typescript
// lib/schemas/user.ts
import { z } from 'zod';
// Basic user schema
export const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email('Invalid email address'),
name: z.string().min(1, 'Name is required').max(100),
username: z
.string()
.min(3, 'Username must be at least 3 characters')
.max(20)
.regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'),
role: z.enum(['admin', 'user', 'moderator']),
bio: z.string().max(500).optional(),
avatarUrl: z.string().url().optional(),
isVerified: z.boolean().default(false),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
});
// Infer TypeScript type from schema
export type User = z.infer<typeof userSchema>;
// Create user schema (without auto-generated fields)
export const createUserSchema = userSchema.omit({
id: true,
isVerified: true,
createdAt: true,
updatedAt: true,
});
export type CreateUserInput = z.infer<typeof createUserSchema>;
// Update user schema (all fields optional except id)
export const updateUserSchema = userSchema
.partial()
.required({ id: true });
export type UpdateUserInput = z.infer<typeof updateUserSchema>;
// Login schema
export const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(8, 'Password must be at least 8 characters'),
rememberMe: z.boolean().optional().default(false),
});
export type LoginInput = z.infer<typeof loginSchema>;
```
## Complex Validations
```typescript
// lib/schemas/order.ts
import { z } from 'zod';
// Address schema with refinements
export 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})?$/, 'Invalid ZIP code'),
country: z.string().default('US'),
});
// Order item schema
export const orderItemSchema = z.object({
productId: z.string().uuid(),
quantity: z.number().int().positive(),
price: z.number().positive(),
});
// Order schema with custom validation
export const orderSchema = z.object({
id: z.string().uuid(),
userId: z.string().uuid(),
items: z.array(orderItemSchema).min(1, 'Order must have at least one item'),
shippingAddress: addressSchema,
billingAddress: addressSchema.optional(),
sameAsShipping: z.boolean().default(true),
totalAmount: z.number().positive(),
status: z.enum(['pending', 'processing', 'shipped', 'delivered', 'cancelled']),
notes: z.string().max(1000).optional(),
createdAt: z.coerce.date(),
}).refine(
(data) => {
// Calculate expected total
const calculatedTotal = data.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
return Math.abs(calculatedTotal - data.totalAmount) < 0.01;
},
{ message: 'Total amount does not match items', path: ['totalAmount'] }
).refine(
(data) => {
// Require billing address if not same as shipping
if (!data.sameAsShipping && !data.billingAddress) {
return false;
}
return true;
},
{ message: 'Billing address required', path: ['billingAddress'] }
);
export type Order = z.infer<typeof orderSchema>;
```
## Transformations
```typescript
// lib/schemas/transforms.ts
import { z } from 'zod';
// Transform and coerce values
export const productSchema = z.object({
name: z.string().transform((val) => val.trim()),
slug: z.string().transform((val) =>
val.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
),
price: z
.string()
.or(z.number())
.transform((val) => {
const num = typeof val === 'string' ? parseFloat(val) : val;
return Math.round(num * 100) / 100; // Round to 2 decimals
}),
tags: z
.string()
.transform((val) => val.split(',').map((t) => t.trim()).filter(Boolean))
.or(z.array(z.string())),
});
// Date parsing with multiple formats
export const dateSchema = z
.string()
.or(z.number())
.or(z.date())
.transform((val) => {
if (val instanceof Date) return val;
if (typeof val === 'number') return new Date(val);
return new Date(val);
})
.refine((date) => !isNaN(date.getTime()), 'Invalid date');
// Preprocess for form data
export const formDataSchema = z.object({
quantity: z.preprocess(
(val) => (val === '' ? undefined : Number(val)),
z.number().int().positive().optional()
),
isActive: z.preprocess(
(val) => val === 'true' || val === true || val === '1',
z.boolean()
),
categories: z.preprocess(
(val) => (typeof val === 'string' ? [val] : val),
z.array(z.string())
),
});
```
## API Validation
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createUserSchema } from '@/lib/schemas/user';
// Generic validation wrapper
async function validateRequest<T>(
request: NextRequest,
schema: z.ZodType<T>
): Promise<{ data: T; error: null } | { data: null; error: NextResponse }> {
try {
const body = await request.json();
const data = schema.parse(body);
return { data, error: null };
} catch (error) {
if (error instanceof z.ZodError) {
return {
data: null,
error: NextResponse.json(
{
error: 'Validation failed',
details: error.errors.map((e) => ({
path: e.path.join('.'),
message: e.message,
})),
},
{ status: 400 }
),
};
}
return {
data: null,
error: NextResponse.json(
{ error: 'Invalid request body' },
{ status: 400 }
),
};
}
}
export async function POST(request: NextRequest) {
const { data, error } = await validateRequest(request, createUserSchema);
if (error) return error;
// data is fully typed as CreateUserInput
const user = await createUser(data);
return NextResponse.json({ user }, { status: 201 });
}
// Query params validation
const searchParamsSchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
search: z.string().optional(),
sortBy: z.enum(['name', 'createdAt', 'price']).default('createdAt'),
order: z.enum(['asc', 'desc']).default('desc'),
});
export async function GET(request: NextRequest) {
const params = Object.fromEntries(request.nextUrl.searchParams);
const result = searchParamsSchema.safeParse(params);
if (!result.success) {
return NextResponse.json(
{ error: 'Invalid query parameters' },
{ status: 400 }
);
}
const { page, limit, search, sortBy, order } = result.data;
// Use validated params...
}
```
## Form Integration
```typescript
// components/UserForm.tsx
'use client';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createUserSchema, type CreateUserInput } from '@/lib/schemas/user';
export function UserForm({ onSubmit }: { onSubmit: (data: CreateUserInput) => void }) {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<CreateUserInput>({
resolver: zodResolver(createUserSchema),
defaultValues: {
role: 'user',
},
});
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<input {...register('name')} placeholder="Name" />
{errors.name && <span className="error">{errors.name.message}</span>}
</div>
<div>
<input {...register('email')} type="email" placeholder="Email" />
{errors.email && <span className="error">{errors.email.message}</span>}
</div>
<div>
<input {...register('username')} placeholder="Username" />
{errors.username && <span className="error">{errors.username.message}</span>}
</div>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create User'}
</button>
</form>
);
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Zod patterns: Define schemas once and derive types. Use refinements for cross-field validation. Implement transforms for data normalization. Create reusable schema compositions. Use safeParse for non-throwing validation.This 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.