Coding
AI Prompt for Validation Functions
Generate bulletproof input validation with this AI prompt: per-field rules, clear error messages, and tests for tricky inputs like empty strings.
The prompt
Role: You are a [LANGUAGE] developer obsessed with robust input validation and great error messages.
Context: I need to validate [WHAT: form input / API payload / CSV rows / etc.] in [LANGUAGE].
Fields and rules:
[FIELD_RULES, e.g. email: required, valid format; age: integer 0-120]
Return format: [RETURN_FORMAT, e.g. list of {field, message} errors, or throw on first error].
Task: 1) Write a validation function covering every rule, including sneaky cases: empty strings, whitespace-only, wrong types, out-of-range numbers, over-long input. 2) Make every error message specific and user-friendly ("Email is required" not "Invalid input"). 3) Provide test cases: one valid input, and one invalid input per rule, with expected results.
Format: Function in a code block, then the test cases as a list with expected outcomes.
Constraints: Validate everything — never trust input. Keep messages actionable: tell the user what to fix, not just what failed. Do not use regex where a simple check suffices, and vice versa.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [WHAT] [FIELD_RULES] [RETURN_FORMAT]
Example input
LANGUAGE=JavaScript, FORM=farm names + owner contact, FIELDS=name (required, 2-100 chars), email (valid format), phone (optional, digits only), herdSize (integer ≥ 0)
How to use this prompt
List every field with its rules — validation code is only as complete as your field list. Specify both layers if you need client and server validation.
Tips for the best results
- Ask for both 'validate and collect all errors' and 'fail fast' versions if you need both.
- Include unicode and emoji in test inputs — they break naive length checks.
- For APIs, ask it to also return the appropriate HTTP status mapping.
Frequently asked questions
Can it handle frontend and backend validation?
It cannot run your form, but it can reason about bypass vectors (empty strings, unicode, huge inputs) and write both layers consistently.
Should validation live on the frontend, backend, or both?
Both: frontend for instant UX feedback, backend as the real security boundary. This prompt can generate the two layers from one rule list so they never drift.