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.

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
- Why Zod beats ad hoc validation
- How to use these prompts
- 15 Zod validation prompts
- React Hook Form + Zod wiring
- Server actions and API routes
- Error messages users understand
- Mistakes AI makes with Zod
- 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,passwordSchemaacross forms - Safe parsing —
safeParsereturns 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:
- Confirm schema is imported in both client form and server handler
- Run
safeParseon server even if client validated - Read error messages aloud — if you cringe, refine copy
15 Zod validation prompts
- Shared email field — “Create
lib/validations/auth.tsexportingemailSchema: 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.” - 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.” - Signup form composite — “Create
signupSchemawith emailSchema, passwordSchema, name (2–80 chars, letters and spaces). AddconfirmPasswordwith.refine()matching password. Export for React Hook Form zodResolver.” - 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[]> }.” - Profile update partial — “Create
profileUpdateSchemaas z.object with optional name, bio (max 500), avatarUrl (url or empty string transformed to null). Use.strict()to reject unknown keys from client.” - 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’.” - 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’.” - 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’.” - 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’.” - File metadata only — “Create
uploadMetaSchemafor 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.” - Settings toggles — “Create
notificationSettingsSchemawith boolean flags emailDigest, marketing, productUpdates — default false, coerce from string ‘true’/’false’ if needed for form posts.” - Array of tags — “Add
tagsSchema: array of strings, max 10 items, each 2–30 chars, dedupe case-insensitive. Error on excess: ‘Maximum 10 tags’.” - Discriminated union action — “Create
adminActionSchemaas z.discriminatedUnion(‘type’, [banUser, resetPassword, extendTrial]). Each variant has type literal and required ids. SafeParse in server action before switch.” - 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.” - 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.”

React Hook Form + Zod wiring
Standard pattern AI should produce after prompt 3 or 4:
useForm({ resolver: zodResolver(signupSchema), defaultValues })- Display
formState.errors.field?.messageunder each input aria-invalidandaria-describedbyon 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:
- Parse input with same schema (or stricter server schema)
- Return 400-shaped object for forms, not throw uncaught ZodError
- 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 value | Choose a plan from the list |
| Expected number, received nan | Enter a valid amount |
| Invalid input | Check 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 —
FormFieldwrapper 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 inputaria-describedbypointing to error span idrole="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.
