Input validation checks progress from coarse to fine — what does each layer verify, from the source of the data down to its meaning?
Source → size → lexical (allowed characters) → syntax (correct format) → semantics (makes sense in context). Reject as early as possible.
* Validate coarse-to-fine — Source, Size, Lexical, Syntax, Semantics — rejecting at the first failure to save processing. *
You validate from cheap, coarse checks to expensive, fine ones, rejecting bad input at the first failure:
| # | Criterion | What to check | Example |
|---|---|---|---|
| 1 | Legitimate source | Verify origin system/user | CSRF token, API key |
| 2 | Reasonable size | Max length/size limits | Username ≤ 255 chars |
| 3 | Lexically valid | Only allowed characters | No <>"'; in names |
| 4 | Syntactically valid | Correct format/structure | Valid email pattern |
| 5 | Semantically valid | Makes sense in context | Birth date not in future |
Why the order is not arbitrary: each layer is cheaper than the one after it and each one narrows what the next has to consider. Checking the source is a token comparison; checking semantics may cost a database lookup. Rejecting at the first failure means a 10 MB junk payload never reaches your regex, and a syntactically broken date never reaches the "is this date plausible?" logic. It is also a defence in itself — a size cap alone kills a whole class of overflow and denial-of-service attempts before any parsing happens.
Tip: memorise it as a ladder of five questions, coarse to fine — Who sent it? How big is it? Which characters? What shape? Does it make sense here? (Source, Size, Lexical, Syntax, Semantics.) Stop at the first "no".
Go deeper:
OWASP Input Validation Cheat Sheet — validation strategy, allowlisting, and where to validate.