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 Form Validation Complete Guide

Zod Form Validation Complete Guide

Build type-safe forms in Google Antigravity applications using React Hook Form with Zod schema validation and server actions.

react-hook-formzodformsvalidationtypescript
by antigravity-team
⭐0Stars
.antigravity
# Zod Form Validation Complete Guide

Create robust, type-safe forms in your Google Antigravity applications using React Hook Form with Zod schema validation. This guide covers form setup, validation patterns, and server action integration.

## Schema Definition

Define validation schemas with Zod:

```typescript
// lib/schemas/prompt.ts
import { z } from "zod";

export const promptSchema = z.object({
  title: z
    .string()
    .min(5, "Title must be at least 5 characters")
    .max(100, "Title must be less than 100 characters"),
  description: z
    .string()
    .min(20, "Description must be at least 20 characters")
    .max(500, "Description must be less than 500 characters"),
  content: z
    .string()
    .min(100, "Content must be at least 100 characters")
    .max(10000, "Content must be less than 10,000 characters"),
  tags: z
    .array(z.string())
    .min(1, "Add at least one tag")
    .max(5, "Maximum 5 tags allowed"),
  category: z.enum(["react", "nextjs", "typescript", "python", "api"], {
    errorMap: () => ({ message: "Please select a category" }),
  }),
  isPublic: z.boolean().default(true),
});

export type PromptFormData = z.infer<typeof promptSchema>;

// Partial schema for drafts
export const promptDraftSchema = promptSchema.partial();
export type PromptDraftData = z.infer<typeof promptDraftSchema>;
```

## Form Component

Build the form with React Hook Form:

```typescript
// components/PromptForm.tsx
"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { promptSchema, type PromptFormData } from "@/lib/schemas/prompt";
import { useTransition } from "react";
import { submitPrompt } from "@/app/actions/prompts";

const CATEGORIES = [
  { value: "react", label: "React" },
  { value: "nextjs", label: "Next.js" },
  { value: "typescript", label: "TypeScript" },
  { value: "python", label: "Python" },
  { value: "api", label: "API Development" },
];

export function PromptForm() {
  const [isPending, startTransition] = useTransition();
  
  const {
    register,
    handleSubmit,
    control,
    formState: { errors, isDirty },
    reset,
    setError,
  } = useForm<PromptFormData>({
    resolver: zodResolver(promptSchema),
    defaultValues: {
      title: "",
      description: "",
      content: "",
      tags: [],
      category: undefined,
      isPublic: true,
    },
  });

  const onSubmit = (data: PromptFormData) => {
    startTransition(async () => {
      const result = await submitPrompt(data);
      
      if (result.error) {
        // Handle server-side validation errors
        if (result.fieldErrors) {
          Object.entries(result.fieldErrors).forEach(([field, message]) => {
            setError(field as keyof PromptFormData, {
              type: "server",
              message: message as string,
            });
          });
        }
        return;
      }
      
      reset();
      // Show success message or redirect
    });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* Title Field */}
      <div>
        <label htmlFor="title" className="block text-sm font-medium mb-2">
          Title
        </label>
        <input
          id="title"
          {...register("title")}
          className={`w-full px-4 py-2 border rounded-lg ${
            errors.title ? "border-red-500" : "border-gray-300"
          }`}
          placeholder="Enter prompt title"
        />
        {errors.title && (
          <p className="mt-1 text-sm text-red-500">{errors.title.message}</p>
        )}
      </div>

      {/* Description Field */}
      <div>
        <label htmlFor="description" className="block text-sm font-medium mb-2">
          Description
        </label>
        <textarea
          id="description"
          {...register("description")}
          rows={3}
          className={`w-full px-4 py-2 border rounded-lg ${
            errors.description ? "border-red-500" : "border-gray-300"
          }`}
          placeholder="Brief description of the prompt"
        />
        {errors.description && (
          <p className="mt-1 text-sm text-red-500">
            {errors.description.message}
          </p>
        )}
      </div>

      {/* Submit Button */}
      <button
        type="submit"
        disabled={isPending || !isDirty}
        className="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
      >
        {isPending ? "Submitting..." : "Submit Prompt"}
      </button>
    </form>
  );
}
```

## Server Action Integration

Handle form submission with server actions:

```typescript
// app/actions/prompts.ts
"use server";

import { promptSchema, type PromptFormData } from "@/lib/schemas/prompt";
import { createClient } from "@/lib/supabase/server";
import { revalidatePath } from "next/cache";

export async function submitPrompt(data: PromptFormData) {
  // Server-side validation
  const result = promptSchema.safeParse(data);
  
  if (!result.success) {
    const fieldErrors: Record<string, string> = {};
    result.error.issues.forEach((issue) => {
      const path = issue.path[0] as string;
      fieldErrors[path] = issue.message;
    });
    return { error: "Validation failed", fieldErrors };
  }

  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();

  if (!user) {
    return { error: "Unauthorized" };
  }

  const { error } = await supabase
    .from("prompts")
    .insert({
      ...result.data,
      user_id: user.id,
      slug: generateSlug(result.data.title),
    });

  if (error) {
    return { error: "Failed to create prompt" };
  }

  revalidatePath("/prompts");
  return { success: true };
}
```

## Best Practices

1. **Schema Reuse**: Share Zod schemas between client and server
2. **Error Mapping**: Transform validation errors to user-friendly messages
3. **Optimistic Updates**: Show immediate feedback while server processes
4. **Field-Level Validation**: Validate on blur for immediate feedback
5. **Accessible Forms**: Include proper labels and ARIA attributes
6. **Progressive Enhancement**: Forms should work without JavaScript

When to Use This Prompt

This react-hook-form prompt is ideal for developers working on:

  • react-hook-form applications requiring modern best practices and optimal performance
  • Projects that need production-ready react-hook-form code with proper error handling
  • Teams looking to standardize their react-hook-form development workflow
  • Developers wanting to learn industry-standard react-hook-form 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 react-hook-form 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 react-hook-form 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 react-hook-form 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 react-hook-form projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...