Implement robust data validation with Zod schemas
# Zod Validation Complete Guide for Google Antigravity
Build type-safe validation with Zod schemas using Google Antigravity IDE.
## Basic Schema Definitions
```typescript
// lib/validations/user.ts
import { z } from "zod";
// String validations
export const emailSchema = z.string()
.email("Invalid email address")
.toLowerCase()
.trim();
export const passwordSchema = z.string()
.min(8, "Password must be at least 8 characters")
.max(100, "Password is too long")
.regex(/[A-Z]/, "Must contain uppercase letter")
.regex(/[a-z]/, "Must contain lowercase letter")
.regex(/[0-9]/, "Must contain number");
// Object schemas
export const userSchema = z.object({
id: z.string().uuid(),
email: emailSchema,
name: z.string().min(1).max(100),
bio: z.string().max(500).optional(),
role: z.enum(["admin", "user", "moderator"]).default("user"),
createdAt: z.date(),
updatedAt: z.date()
});
// Create/Update schemas
export const createUserSchema = userSchema.omit({
id: true,
createdAt: true,
updatedAt: true
}).extend({
password: passwordSchema,
confirmPassword: z.string()
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"]
});
// Types from schemas
export type User = z.infer<typeof userSchema>;
export type CreateUserInput = z.infer<typeof createUserSchema>;
```
## Complex Validation Patterns
```typescript
// Discriminated unions
export const paymentMethodSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("card"),
cardNumber: z.string().regex(/^\d{16}$/),
expiryMonth: z.number().min(1).max(12),
expiryYear: z.number().min(new Date().getFullYear()),
cvv: z.string().regex(/^\d{3,4}$/)
}),
z.object({
type: z.literal("bank"),
accountNumber: z.string().min(10).max(17),
routingNumber: z.string().length(9)
}),
z.object({
type: z.literal("paypal"),
email: z.string().email()
})
]);
// Transform and preprocess
export const searchParamsSchema = z.object({
page: z.coerce.number().positive().default(1),
limit: z.coerce.number().positive().max(100).default(20),
sort: z.enum(["newest", "oldest", "popular"]).default("newest"),
tags: z.preprocess(
(val) => (typeof val === "string" ? val.split(",") : val),
z.array(z.string()).optional()
)
});
```
## Form Integration
```typescript
// components/forms/UserForm.tsx
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { createUserSchema, type CreateUserInput } from "@/lib/validations/user";
export function UserForm({ onSubmit }: { onSubmit: (data: CreateUserInput) => Promise<void> }) {
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<CreateUserInput>({
resolver: zodResolver(createUserSchema)
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} placeholder="Email" />
{errors.email && <span>{errors.email.message}</span>}
<input type="password" {...register("password")} />
{errors.password && <span>{errors.password.message}</span>}
<button type="submit" disabled={isSubmitting}>Create</button>
</form>
);
}
```
## Best Practices
1. **Create reusable schemas** for common fields
2. **Use discriminated unions** for variant types
3. **Implement refinements** for cross-field validation
4. **Export inferred types** alongside schemas
5. **Use transform** for data normalization
6. **Provide clear error messages**
7. **Validate at API boundaries**
Google Antigravity helps generate Zod schemas from TypeScript types and database schemas.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.