Input Validation and Sanitization
What you'll learn: How to implement whitelist validation, type checking, and proper escaping as defense-in-depth measures against SQL injection and other attacks.
The Core Idea
Even when you use parameterized queries (the primary defense against SQL injection), you should still validate and sanitize user input as an additional security layer. Think of it like airport security: your boarding pass gets you through the gate (parameterized queries), but you still go through metal detectors and bag checks (validation and sanitization) for extra safety.
Three Key Defense Techniques
Whitelist Validation
Instead of trying to block bad input (blacklist), only allow known-good patterns. For example, if you expect a username, accept only alphanumeric characters and underscores:
import re
def validate_username(username):
# Only allow letters, numbers, underscore
if re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
return True
return False
Type Checking
Ensure input matches the expected data type. If you expect an integer ID, convert and validate it:
def validate_user_id(user_input):
try:
user_id = int(user_input)
if user_id > 0:
return user_id
except ValueError:
return None
return None
Proper Escaping
When validation alone isn't sufficient (like accepting free-text comments), escape special characters that could be interpreted as commands. Remove or encode characters like quotes, semicolons, and SQL keywords.
Defense-in-Depth
These techniques complement—not replace—parameterized queries. They catch errors earlier, reduce attack surface, and protect against logic flaws or forgotten edge cases.
Key Takeaway: Input validation (whitelist patterns, type checking) and sanitization (escaping dangerous characters) provide essential defense-in-depth layers that work alongside parameterized queries to prevent SQL injection and other input-based attacks.