ismycodesafe.com

Input Validation: Allowlist, Server-Side, and Why It Is Not Enough

Input validation is one of the oldest pieces of security advice and one of the most often done wrong. Here is how to do it right, and why it is a layer rather than a silver bullet.

··8 min read·By ismycodesafe.com Security Team
Allowlist validation defines what is valid and rejects the rest; denylist validation blocks known-bad and leaks on new bypasses

Key Takeaway

Input validation checks that incoming data matches the expected type, length, format, and range before processing. Use allowlist (not denylist) validation, validate on the server (never trust the client), and combine it with context-aware output encoding to stop injection. Validation is defense in depth, not a replacement for parameterized queries.

What Is Input Validation?

Input validation is checking that incoming data matches the expected type, length, format, and range before your application does anything with it. A postcode should look like a postcode. An age should be a positive integer in a sane range. A username should match a defined character set and length. Anything that does not fit gets rejected at the door.

The point is to shrink the attack surface. Every field that accepts arbitrary bytes is a field an attacker can probe. Validation narrows what each field will even accept, so a lot of malformed and malicious input never reaches the logic behind it.

There are two kinds of check. Syntactic validation asks whether a value has the right form: digits only, 3 to 20 characters, a real date. Semantic validation asks whether it makes sense here: the start date comes before the end date, the order ID belongs to the logged-in user. Access-control bugs like IDOR live in the second kind, and no regex catches them.

Allowlist vs Denylist

Use an allowlist: define exactly what is valid and reject everything else. The opposite approach, a denylist that enumerates known-bad patterns and blocks them, is the single most common way validation goes wrong.

A denylist that strips <script> misses <img onerror>, <svg onload>, mixed-case <ScRiPt>, and a dozen encodings you did not think of. You are playing whack-a-mole against an attacker who only has to find one gap. An allowlist flips the burden: a username matched against ^[a-z0-9_]{3,20}$ rejects every payload that is not lowercase letters, digits, or underscores, including attacks that did not exist when you wrote the rule. It fails closed.

Validate on the Server

All security validation runs server-side. Client-side checks in the browser are good for user experience, instant feedback before a round trip, but they are trivially bypassed. An attacker does not use your form; they call your API directly with curl and send whatever they want.

// Client-side validation only - bypassed in seconds:
curl -X POST https://example.com/api/profile \
  -d 'username=<svg onload=alert(1)>'
// The browser form would have blocked this. The API did not.

Treat client-side validation as convenience and server-side validation as the boundary. If you can only do one, do the server.

Server-Side Validation in Code

Most stacks have a schema library that does this in a few lines. The pattern is the same everywhere: describe the allowed shape once, parse every request body against it, and reject anything that fails before your handler touches it. The OWASP Input Validation Cheat Sheet describes the rules. This is what they look like in Node.js with Zod:

import { z } from "zod";

const Profile = z.object({
  username: z.string().regex(/^[a-z0-9_]{3,20}$/),
  age: z.number().int().min(13).max(120),
  country: z.enum(["NO", "SE", "DK"]),
}).strict();

app.post("/api/profile", (req, res) => {
  const parsed = Profile.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: "invalid input" });
  saveProfile(parsed.data);
  res.sendStatus(204);
});

By default Zod strips keys it does not know, which is already safer than passing req.body straight through. .strict() goes one step further and rejects the request, so a client that sends "isAdmin": true gets a 400 you can log instead of a silent pass.

The same rules in Python with FastAPI and Pydantic:

from typing import Literal
from pydantic import BaseModel, ConfigDict, Field

class Profile(BaseModel):
    model_config = ConfigDict(extra="forbid")
    username: str = Field(pattern=r"^[a-z0-9_]{3,20}$")
    age: int = Field(ge=13, le=120)
    country: Literal["NO", "SE", "DK"]

@app.post("/api/profile", status_code=204)
def update_profile(profile: Profile):
    save_profile(profile)

FastAPI runs the model before your function and answers 422 on anything that does not fit. extra="forbid" does the job of .strict(). One difference to know: Pydantic converts types by default, so the string "30" becomes the integer 30. Add strict=True to the config if a wrong type should be an error.

Validation Is Not the Whole Fix

Here is the part that trips people up. Validation reduces risk, but it is not what stops injection. SQL injection is stopped by parameterized queries, which keep data and code separate no matter what the data contains. XSS is stopped by context-aware output encoding, applied when data is written into a page. Validation works alongside those as defense in depth.

Three layers: validate input with an allowlist, parameterize queries to stop SQL injection, encode output to stop XSS
Validation is the first layer. Parameterization and encoding are the ones that actually neutralize injection.

The reason the distinction matters: plenty of valid input is still dangerous in the wrong context. The name O'Brien is a perfectly valid name and a perfectly good way to break a string-concatenated SQL query. Validation lets it through, correctly, because it is real data. Parameterization is what keeps it from becoming code.

A Practical Checklist

  • Allowlist every field by type, length, format, and range. Reject, do not sanitize, when you can.
  • Validate server-side on every request, treating client checks as UX only.
  • Validate at the boundary, as data enters the system, not scattered deep in the logic.
  • Pair with parameterized queries and output encoding, so a valid-but-dangerous value cannot turn into an injection.
  • Normalize before you validate, decoding and canonicalizing input first so an encoded payload cannot slip past the check.

Test Your Site

Validation bugs surface when you send the input the developer assumed would never arrive: wrong type, absurd length, an encoded payload, a missing field. We built ismycodesafe after watching how reliably AI-assisted code generates the optimistic version of a handler, the one that trusts the request shape and validates nothing, because the prompt asked for the feature, not the guard. Our scanner probes your live endpoints for the configuration and response patterns that give this away.

Scan My Website for Free

Check your website right now

200+ security checks in 60 seconds. Free, no signup required.

Scan My Website (Free)

Claude AI helped me with phrasing and proofreading in this article.

Roy Morken

I build ismycodesafe.com, the scanner these guides are written around. I'm an indie security practitioner based in Norway, and I write about the checks the scanner runs and how to fix what they find. Questions or corrections: help@ismycodesafe.com.