Database Input Validation with AI Prompts

TL;DR

Validation is defense in depth. Even with parameterized queries, you should validate input types, lengths, and formats before they reach your database. These prompts help you add validation layers using Zod, Joi, or custom validators.

Schema Validation with Zod

Copy this prompt to generate Zod validation schemas that match your database tables. Your AI will create insert schemas (all required fields), update schemas (all optional), and query/filter schemas with proper error messages for each field constraint.

AI Prompt

Zod Schema Validation

Create Zod schemas to validate input before database operations.

For these database tables, create validation schemas:

Table: users

  • email: valid email, max 255 chars
  • username: alphanumeric, 3-30 chars
  • age: optional, integer 13-120

Table: posts

  • title: string, 1-200 chars
  • content: string, max 50000 chars
  • status: enum (draft, published, archived)
  • tags: array of strings, max 10 items

Create:

  1. Insert schemas (all required fields)
  2. Update schemas (all fields optional)
  3. Query/filter schemas (for search params)

Include proper error messages for each validation.

Type Coercion and Sanitization

Use this prompt to generate input sanitization helpers that safely coerce and clean data from URLs, JSON bodies, and form submissions. You'll get functions for type coercion, whitespace trimming, email normalization, HTML stripping, and date parsing.

AI Prompt

Input Sanitization

Add input sanitization for database operations.

Input sources:

  • URL parameters (always strings)
  • JSON body (may have wrong types)
  • Form data (strings)

Create sanitization helpers that:

  1. Coerce string IDs to integers safely
  2. Trim whitespace from strings
  3. Normalize email to lowercase
  4. Strip HTML/scripts from text fields
  5. Parse dates from various formats
  6. Handle null vs undefined vs empty string

Language: TypeScript/JavaScript/Python

Return validation errors rather than throwing for invalid input.

Query Parameter Validation

This prompt asks your AI to create reusable validation for database query parameters. You'll get middleware that validates pagination, whitelisted sort columns, date range filters, and search strings with sensible defaults for missing values.

AI Prompt

Validate Query Params

Create validation for database query parameters.

Parameters to validate:

  1. Pagination: page (int >= 1), limit (int 1-100)
  2. Sorting: orderBy (whitelist of columns), order (asc/desc)
  3. Filtering: status, dateFrom, dateTo, search
  4. IDs: must be valid format (UUID, integer, etc)

Requirements:

  • Whitelist allowed orderBy columns
  • Validate date ranges make sense (from < to)
  • Limit search string length
  • Set sensible defaults for missing params
  • Reject unexpected parameters

Framework: Express/Fastify/Next.js API routes

Create middleware or helper functions for reuse.

Validation isn't a replacement for parameterization: Always use parameterized queries even with validated input. Validation catches bad data early but doesn't prevent injection on its own.

Database Constraint Validation

Paste this prompt to generate application-level validation that mirrors your database constraints. Your AI will create validators matching VARCHAR lengths, CHECK constraints, regex patterns, and foreign key references with user-friendly error messages instead of raw database errors.

AI Prompt

Match DB Constraints

Create validation that matches my database constraints.

Database schema:

  • users.email: VARCHAR(255) UNIQUE NOT NULL
  • users.username: VARCHAR(50) UNIQUE, regex ^a-z0-9_+$
  • posts.title: VARCHAR(200) NOT NULL
  • posts.author_id: FOREIGN KEY to users.id

Create validation that:

  1. Enforces the same length limits as VARCHAR
  2. Matches CHECK constraints and regex patterns
  3. Pre-validates foreign key IDs exist (optional)
  4. Returns friendly error messages, not DB errors

Bonus: Generate validation from Prisma/Drizzle schema if available.

Pro tip: Validate at the API boundary, not deep in your code. Catch bad input early in your request handlers before it propagates through your application.

Should I validate on the frontend and backend?

Yes. Frontend validation improves UX with instant feedback. Backend validation is required for security since frontend validation can be bypassed.

How do I handle validation for optional fields?

Use .optional() or .nullable() in your schema. Distinguish between a field being absent, null, and an empty string based on your requirements.

Further Reading

Want to understand the vulnerability before fixing it? These guides explain what's happening and why.

Scan for Missing Validation

Find database operations that lack proper input validation.

AI Fix Prompts

Database Input Validation with AI Prompts