# Input Validation ## Rule Validate all input. Allowlist > blocklist. **Source:** [OWASP Input Validation Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html) ## Correct Pattern ```python import re from typing import Optional # Allowlist: only permit known-good patterns VALID_USERNAME = re.compile(r'^[a-zA-Z0-9_]{3,20}$') VALID_EMAIL = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') def validate_username(username: str) -> Optional[str]: """Return sanitized username or None if invalid.""" if not username: return None username = username.strip() if VALID_USERNAME.match(username): return username return None def validate_positive_int(value: str, max_value: int = 10000) -> Optional[int]: """Parse and validate positive integer with upper bound.""" try: n = int(value) if 0 < n <= max_value: return n except (ValueError, TypeError): pass return None ``` ## Incorrect Pattern ```python # Wrong: blocklist approach (attackers find bypasses) def sanitize(s): bad = ["