Input Validation and Sanitization
You'll learn how to prevent injection attacks by validating inputs against safe patterns, encoding dangerous characters, and escaping outputs based on where they're used.
The Core Problem
Even with parameterized queries protecting your database, user input flows through many contexts: HTML pages, JavaScript, URLs, file systems, and more. Each context has its own dangerous characters. Input validation decides if data is acceptable at all. Sanitization transforms input to remove or neutralize threats. Output escaping ensures data displays safely in its final context.
Three Lines of Defense
1. Allowlist Validation
Define what's allowed, not what's forbidden. For a username, accept only [a-zA-Z0-9_-] rather than trying to block every special character. Reject anything that doesn't match. Think of it like a bouncer checking IDs—clear rules about who gets in, everyone else stays out.
import re
def validate_username(username):
# Allowlist: only alphanumeric, underscore, hyphen
if re.match(r'^[a-zA-Z0-9_-]+$', username):
return True
return False # Reject anything else
2. Proper Encoding
If you must include user data in SQL, HTML, or JSON, encode it for that context. HTML-encode < to <, SQL-escape quotes (though parameterized queries are better).
3. Context-Aware Output Escaping
Escape data based on where it appears. User input in HTML body needs HTML-escaping. In a JavaScript string, use JavaScript-escaping. In a URL parameter, use URL-encoding. Wrong context = bypassed protection.
from html import escape
user_input = "<script>alert('xss')</script>"
safe_html = escape(user_input) # Becomes <script>...
Key Takeaway:
Validate inputs with allowlists, encode for the data format, and escape outputs based on context—never trust user data in any processing pipeline.