Developer refactoring multi-file code with AI prompts

15 Prompts for Zod Validation, Forms, and Error Messages That Users Understand

Zod validation prompts for vibe-coded forms turn “add a signup form” into schemas that match your database, error messages humans understand, and server actions that reject bad data before it hits Postgres. AI defaults to loose types, generic “Invalid input” toasts, and client-only checks that curl bypasses in seconds. These 15 copy-paste prompts fix the pattern — not just one field. Updated November 2026.

Form validation schema code with user-friendly error messages in a Next.js application
Good validation feels invisible until it saves you from bad rows and angry support tickets.

Use alongside auth for vibe-coded Next.js apps — signup and profile forms are where Zod pays off first. Before production, run the security checklist to catch server actions that skip schema validation entirely.

Table of contents

  1. Why Zod beats ad hoc validation
  2. How to use these prompts
  3. 15 Zod validation prompts
  4. React Hook Form + Zod wiring
  5. Server actions and API routes
  6. Error messages users understand
  7. Mistakes AI makes with Zod
  8. FAQ

Why Zod beats ad hoc validation

Zod gives you one schema for TypeScript inference, client hints, and server enforcement. Vibe-coded apps often validate in React with regex copy-pasted from Stack Overflow while the API route trusts JSON body shape — classic split-brain.

Benefits for solo builders:

  • Single source of truth — Export z.infer<typeof schema> types to components
  • Composable fields — Reuse emailSchema, passwordSchema across forms
  • Safe parsing — safeParse returns discriminated errors without try/catch soup
  • i18n-ready — Map error codes to copy in one layer

Install: npm i zod. For forms: @hookform/resolvers/zod. AI knows Zod — it just does not apply it consistently until you prompt structure.

How to use these prompts

Each prompt assumes Next.js App Router, TypeScript, and a lib/validations/ folder. Replace table and field names. After each generation:

  1. Confirm schema is imported in both client form and server handler
  2. Run safeParse on server even if client validated
  3. Read error messages aloud — if you cringe, refine copy

15 Zod validation prompts

  1. Shared email field — “Create lib/validations/auth.ts exporting emailSchema: trim, lowercase, valid email, max 254 chars, custom error map — empty → ‘Email is required’, invalid → ‘Enter a valid email like name@company.com’. Export type Email.”
  2. Password with strength rules — “Add passwordSchema: min 8, max 128, at least one letter and one number, optional special char. Errors: too short → ‘Use at least 8 characters’, weak → ‘Add a number to your password’. No arbitrary regex error strings.”
  3. Signup form composite — “Create signupSchema with emailSchema, passwordSchema, name (2–80 chars, letters and spaces). Add confirmPassword with .refine() matching password. Export for React Hook Form zodResolver.”
  4. Login minimal — “Create loginSchema: emailSchema + password (required string, no strength check on login). Server action must use same schema; return field errors as { fieldErrors: Record<string, string[]> }.”
  5. Profile update partial — “Create profileUpdateSchema as z.object with optional name, bio (max 500), avatarUrl (url or empty string transformed to null). Use .strict() to reject unknown keys from client.”
  6. Phone optional US format — “Add optional phoneSchema: empty string → undefined, else E.164 or US (XXX) XXX-XXXX with refine. Error: ‘Enter a valid US phone number or leave blank’.”
  7. Date range booking — “Create bookingSchema: startDate and endDate as z.coerce.date(), end >= start, neither in past (server timezone UTC). Field-level errors on endDate: ‘End date must be after start date’.”
  8. Money amount cents — “Create amountCentsSchema: z.coerce.number().int().min(50).max(99999999). Error messages in dollars for display helper. Reject floats with ‘Amount must be whole cents’.”
  9. Slug from title — “Add slugSchema: lowercase, hyphenated, 3–60 chars, regex ^[a-z0-9]+(?:-[a-z0-9]+)*$. Transform title to suggested slug. Error: ‘URL slug can only use lowercase letters, numbers, and hyphens’.”
  10. File metadata only — “Create uploadMetaSchema for client-reported file name, size bytes, mime — max name 255, size max 10MB, mime enum image/jpeg|png|pdf. Note: actual upload must re-validate server-side.”
  11. Settings toggles — “Create notificationSettingsSchema with boolean flags emailDigest, marketing, productUpdates — default false, coerce from string ‘true’/’false’ if needed for form posts.”
  12. Array of tags — “Add tagsSchema: array of strings, max 10 items, each 2–30 chars, dedupe case-insensitive. Error on excess: ‘Maximum 10 tags’.”
  13. Discriminated union action — “Create adminActionSchema as z.discriminatedUnion(‘type’, [banUser, resetPassword, extendTrial]). Each variant has type literal and required ids. SafeParse in server action before switch.”
  14. Search query sanitization — “Create searchQuerySchema: trim, min 1 max 100, strip angle brackets, optional page z.coerce.number().int().min(1).default(1). Use in GET handler and search input.”
  15. API envelope parser — “Create parseRequestBody<T>(schema, req) helper: read json, safeParse, return { data } or { error: flatten field errors, status 400 }. Use in all POST API routes in app/api.”
Developer using AI prompts to generate Zod schemas for form validation in TypeScript
Prompts 1–5 cover auth; 6–10 cover SaaS data shapes most vibe apps need.

React Hook Form + Zod wiring

Standard pattern AI should produce after prompt 3 or 4:

  • useForm({ resolver: zodResolver(signupSchema), defaultValues })
  • Display formState.errors.field?.message under each input
  • aria-invalid and aria-describedby on inputs for accessibility
  • Disable submit while isSubmitting; show server errors in banner

Prompt: “Wire signup form with React Hook Form + zodResolver(signupSchema). Inline errors below fields. On server action fieldErrors, call setError for each field. No alert() for validation.”

Avoid validating on every keystroke for password strength — validate on blur or submit to reduce noise.

Server actions and API routes

Client Zod is UX. Server Zod is security. Every server action that mutates data:

  1. Parse input with same schema (or stricter server schema)
  2. Return 400-shaped object for forms, not throw uncaught ZodError
  3. Log parse failures at warn level with user id, not raw body (PII)

Prompt 15’s envelope helper prevents drift — one parse path for all routes. Pair with tests for AI-generated code: unit test schemas with valid/invalid fixtures.

Error messages users understand

Rules for copy AI rarely follows:

  • Say what to do — “Enter a valid email” beats “Invalid type”
  • No jargon — Hide Zod issue codes from users
  • One error per field — Pick highest priority issue
  • Match label — If label says “Work email”, error says “Work email is required”
  • Consistent tone — Short, neutral, no blame
Bad (AI default)Better
String must contain at least 8 character(s)Use at least 8 characters
Invalid enum valueChoose a plan from the list
Expected number, received nanEnter a valid amount
Invalid inputCheck the highlighted fields

Centralize copy in errorMap on z.setErrorMap or per-schema .email({ message: '...' }).

Mistakes AI makes with Zod

  • Client-only validation — Fix with mandatory server safeParse in prompt 15
  • z.string() for numbers — Use z.coerce.number() for form fields
  • optional() vs nullable() confusion — Pick one convention per project
  • Huge schemas in component files — Move to lib/validations
  • Leaking stack traces on ZodError — Catch and return generic 400
  • Different schemas client vs server — Import shared module only

For multi-step wizards, use superRefine on final step or per-step partial schemas — prompt: “Multi-step onboarding: step1Schema, step2Schema, merged onboardingSchema for final submit.”

Advanced patterns worth one extra prompt

After the base 15, add:

  • Async refine — Check email uniqueness with debounced server call; prompt for z.string().email().refine(async …) with abort signal
  • Transform pipelines — Trim strings project-wide with z.preprocess
  • OpenAPI alignment — If you generate API docs, mention zod-to-openapi in prompt for shared schemas

Validation is not a substitute for authz — schema proves shape, not permission. Check user can edit row after parse.

Form patterns that pair with Zod

Beyond schemas, structure forms for maintainability:

  • Field components — FormField wrapper accepts name, label, schema slice, renders error from formState
  • Default values from server — Load profile in RSC, pass to client form as defaultValues — avoids flash of empty fields
  • Optimistic UI guard — Disable submit until client parse passes; server still re-validates
  • Reset on success — Contact forms reset; settings forms keep values and show toast

Prompt: “Create reusable FormInput component using React Hook Form Controller, label, error text, aria attributes. Use for all auth and settings forms.”

Accessibility and validation UX

Screen reader users need errors announced. Pattern:

  • aria-invalid={!!error} on input
  • aria-describedby pointing to error span id
  • role="alert" on error container when submit fails
  • Focus first invalid field on submit — form.setFocus('email')

Zod validation prompts for vibe-coded forms fail accessibility review when AI only adds red border CSS. Include a11y requirements in every form prompt — cheaper than retrofitting later.

Client schema vs server schema

Sometimes server needs stricter rules:

  • Client signup: password min 8 for UX
  • Server signup: password min 12 if policy changed; reject breached passwords via Have I Been Pwned API
  • Client profile: bio optional
  • Server profile: bio max 500 even if client schema said 1000 during old deploy

Pattern: export signupSchemaClient and signupSchemaServer where server extends client with .superRefine. Document why they differ — future you will merge them incorrectly otherwise.

Integrating with server actions end-to-end

Complete flow prompt: “Create signup server action: parse body with signupSchemaServer, hash password, insert user, return { success } or { fieldErrors }. Client form uses signupSchemaClient with zodResolver. Map fieldErrors to setError. Log Zod failures without PII.”

Test with invalid payloads via curl against action endpoint — client bypass is not theoretical. Security checklist item: every mutation has server-side schema.

Real-world form examples

Waitlist form — email only, honeypot field validated empty, rate limit on server action. Schema: emailSchema plus hidden website field max length 0.

Onboarding wizard — step schemas merged with .merge() on final submit; intermediate steps validate partial objects so users cannot skip required company name on step 3.

Admin ban user — discriminated union with reason enum and optional note max 280 chars — prevents free-text injection in audit log display.

These patterns appear in every vibe-coded SaaS eventually. Building schema library once with prompts 1–15 saves weeks of inconsistent validation across features shipped by different AI sessions.

FAQ

Zod vs Yup vs Valibot?

Zod dominates TypeScript + Next.js tutorials in 2026. Valibot is lighter; Yup is legacy in many greenfield repos. Pick Zod for AI codegen consistency.

Should I validate query params?

Yes. Use zod on searchParams in page props and route handlers — AI forgets page=abc breaks pagination.

How do I test Zod schemas?

Vitest table-driven tests: input → expected success or error message key. Fast, no browser.

Does Zod work with server components?

Parse in server components and actions only — do not import client-only form libs in RSC files.

What about i18n?

Return error codes from schema (custom issue codes) and map to translations in UI layer — do not embed English in schema if you ship multiple locales.

Can Zod replace database constraints?

No. Keep NOT NULL, UNIQUE, and CHECK in Postgres. Zod is app layer; DB is last line of defense.

How do I validate file uploads with Zod?

Validate metadata only in Zod — name, size, mime enum. Actual bytes checked server-side with sharp or bucket policy. Prompt 10 covers metadata schema; pair with storage security guide.

Should I use zod-form-data for server actions?

Yes when actions receive FormData instead of JSON — zod-form-data adapter parses multipart fields consistently. AI often hand-parses FormData with missing type coercion.

Soft CTA: Pick the messiest form in your app — run prompts 3, 4, and 15 in order tonight. One shared schema file and server parse helper fixes more production bugs than another UI polish pass.

Leave a Reply

Your email address will not be published. Required fields are marked *