Input Validation and Sanitization
What you'll learn: How to protect your web applications by properly checking and cleaning user input before it reaches your code or database.
The Core Problem
When users submit data to your web application—through forms, URLs, or API calls—you cannot trust that input to be safe or well-formed. Malicious users can inject scripts, SQL commands, or other harmful payloads. Input validation and sanitization are your first line of defense against XSS and other injection attacks.
Validation vs. Sanitization
Validation means checking that input matches your expectations. Think of it like a bouncer at a club: does this input have the right format, length, and type? If not, reject it entirely.
Sanitization (or escaping) means transforming potentially dangerous input into a safe form. It's like defusing a bomb—you don't reject it, but you neutralize the dangerous parts.
How They Work Together
For effective XSS prevention, apply both techniques:
-
Validate early: Check that email addresses look like emails, numbers are actually numbers, and dates are valid dates. Use allowlists (permitted characters/patterns) rather than denylists (blocked characters).
-
Sanitize before output: When displaying user input in HTML, escape special characters. Convert
<to<,>to>,"to", etc. This prevents browsers from interpreting user input as executable code. -
Context matters: Sanitize differently for HTML content, HTML attributes, JavaScript strings, and URLs. A
<script>tag is dangerous in HTML but harmless in plain text.
Think of validation as your quality gate and sanitization as your safety wrapper—validation keeps obviously bad data out, while sanitization ensures anything that gets through can't cause harm when used.
Key Takeaway: Never trust user input—validate to ensure data meets expected formats, and sanitize (escape) output based on context to prevent malicious code execution in browsers.