How to validate user input — 6 steps the AI skips

Ask an agent to "add a form" and it will. With required in the markup, with nice red highlighting. It looks validated.
Then someone sends a request past the form — with curl, from a console, from their own script — and discovers there are no server checks at all. Not one.
Let's do it properly, step by step. An honest framing first: validation is not your main defence against injection. OWASP says it plainly: it "should not be used as the primary method of preventing XSS, SQL Injection and other attacks". Those are stopped by parameterized queries and correct output encoding. Validation is for something else: keeping junk out of your database and stopping your logic from crashing on emptiness.
Step 1. Accept that the client can lie
There's one rule and it isn't up for debate. OWASP: validation "must be implemented on the server-side before any data is processed by an application's functions, as any JavaScript-based input validation performed on the client-side can be circumvented by an attacker".
required, maxlength, type="email" are conveniences for a human. Two clicks in devtools removes them. Server-side checking is the only kind that counts.
Step 2. Describe a schema instead of a pile of ifs
Don't hand-write twenty checks. Describe what correct data looks like, as one object. That's documentation and validation in one.
import { z } from "zod";
const Feedback = z.object({
email: z.email(),
topic: z.enum(["bug", "idea", "billing"]),
message: z.string().trim().min(10).max(2000),
rating: z.number().int().min(1).max(5),
}).strict();
Two details this was written for.
z.enum([...])is your allowlist. Not "let's block bad topics" but "there are exactly three, everything else is rejected"..strict()forbids unknown keys. Otherwise someone sends{"role": "admin"}along with their feedback, and your code cheerfully writes the whole object to the database.
Step 3. Check at the entrance, before any logic
One check right at the edge — and from there on you're working with data you trust.
export async function POST(req) {
const result = Feedback.safeParse(await req.json());
if (!result.success) {
return Response.json({ error: "Check the form fields" }, { status: 400 });
}
const data = result.data; // from here on — clean data only
}
safeParse returns a result instead of throwing, so the error path reads calmly. If the data format itself is new to you, see our explainer on what JSON is.
Step 4. Normalize first, validate second
The order matters more than it looks. Check before you normalize and you'll let duplicates and oddities through.
- Trim the edges —
.trim()in the schema above. - Lowercase the email. Otherwise
[email protected]and[email protected]create two accounts. - Normalize Unicode. Accented letters have two different representations. The same name stops matching itself:
const name = raw.normalize("NFC").trim();
On letters, by the way: for free-form text OWASP recommends normalization and character-category allowlisting rather than banning characters from a list. Otherwise the first casualty is the person named O'Brien — their apostrophe is real, and somehow it's always the one caught by the "anti-SQL injection" filter.
Step 5. Put limits where there usually aren't any
The single most common omission — by agents and humans alike — is an upper bound.
- Text length. Without
max()someone will send a megabyte into your "message" field. - Request body size. Set on the server or proxy, not in the handler.
- Number ranges.
quantity: -5in a cart is a refund, if nothing checks. - Number of requests. A valid form submitted a thousand times is also a problem — see rate limiting for that.
For email, OWASP has a separate recommendation that removes a lot of pain: don't try to write the perfect regex. Do a basic check, and let the mail server give the final verdict when it accepts or rejects the address.
Files are their own story. Never trust the filename extension or the Content-Type header: both come from the client and both change in one line. Detect the type from the file's first bytes, and generate your own name on disk:
const name = crypto.randomUUID() + ".webp"; // not file.originalname
That way no file on your server carries a name invented by a stranger.
Step 6. Answer clearly — and give nothing away
An error should help the human and reveal nothing about your server.
// for a human
{ "error": "Message must be 10–2000 characters" }
// not this
{ "error": "PG::StringDataRightTruncation at users.message" }
A database exception text is a free hint about your schema. Put the details in the logs and return a short human explanation.
What you'll end up with
Run the six steps and you get exactly one point where data becomes trusted. Before it: "something arrived". After it: an object of a known shape.
Check yourself quickly — send a request past the form, with curl.
curl -X POST https://your-site.com/api/feedback \
-H "Content-Type: application/json" \
-d '{"email":"nope","message":"hi","role":"admin"}'
You should get a 400 and a short explanation. If you get 200, your validation lives only in the browser — which means it doesn't exist.
So client-side checks aren't needed at all?
They are, just not for security. A browser check gives an instant answer and saves the person from submitting blind. It simply guarantees nothing — the server has to check everything again.
Is validation enough to stop worrying about injection?
No, and that's the big misunderstanding around this topic. Validation filters out junk; injection is stopped by parameterized database queries and correct HTML output. Treat them as two separate jobs that happen to live next door.
The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.





