Input Validation and Sanitization
You'll learn how to filter and clean user input to prevent malicious data from entering your application.
While output encoding protects you at the display layer, input validation catches bad data at the entry point. Think of it as airport security versus a safety net: validation is the checkpoint that rejects dangerous items before they board; encoding is the net that makes already-boarded items harmless when they're used.
Allowlist-Based Input Validation
The safest approach is allowlist validation: only permit known-good patterns. Instead of blocking <script> tags (which attackers can bypass countless ways), define what is allowed:
- Email fields: accept only
alphanumeric@alphanumeric.domain - Usernames:
[a-zA-Z0-9_]with length limits - Phone numbers: digits and specific delimiters only
Allowlists are far more secure than denylists (blocklists), which try to enumerate all possible bad inputs—an impossible task against creative attackers.
HTML Sanitization Libraries
When you must accept rich content (like forum posts), use battle-tested HTML sanitization libraries rather than writing your own:
- DOMPurify (JavaScript)
- Bleach (Python)
- HTML Purifier (PHP)
These libraries parse HTML, strip dangerous elements (<script>, <iframe>, event handlers), and return safe HTML. They understand the nuances of browser parsing that manual regex filtering cannot handle.
Limitations of Input Filtering
Important caveat: Input validation alone isn't bulletproof. Attackers craft polyglot payloads that look safe to validators but execute in different contexts. Data considered "safe" for HTML might be dangerous in JavaScript strings or URLs. That's why defense in depth matters—combine validation with output encoding and CSP.
Input filtering also risks false positives (blocking legitimate data) or false negatives (missing novel attacks).
Key Takeaway:
Use allowlist-based validation to reject bad input early, leverage proven HTML sanitization libraries for rich content, but never rely on input filtering alone—always pair it with output encoding and other defenses.