Input Validation and Injection Flaws
Core concepts
Injection happens when untrusted data is interpreted as code or syntax by a downstream interpreter: SQL, NoSQL, OS shell, LDAP, XPath, template engines, and the browser (XSS). The durable defense is context-aware output encoding plus parameterization, not blocklists. Know SQL injection classes (in-band/union, error-based, blind boolean, time-based), and the fix: prepared statements with bound parameters, least-privilege database accounts, and allowlisted identifiers for things parameters cannot bind (table/column names).
XSS and command injection
Know reflected, stored, and DOM-based XSS; the defense is contextual output encoding (HTML body, attribute, JavaScript, URL, CSS) plus a strict Content-Security-Policy with nonces or hashes, and avoiding innerHTML, eval, and dangerouslySetInnerHTML. Sanitization (e.g., an allowlist HTML sanitizer) is for cases where users must submit markup. For command injection, avoid shell invocation entirely; use argument-vector APIs, allowlist inputs, and never concatenate into a shell string. For all input: validate on a positive allowlist (type, length, range, format) at the boundary, but treat validation as defense-in-depth, not the injection fix.
Traps
Questions claim input validation alone stops SQLi or XSS; confuse encoding with escaping or with sanitization; assume stored XSS needs user interaction (it does not); or forget second-order injection where stored data is later concatenated into a query.
Rule of thumb
Keep data and code separate: bind parameters, encode at output in the exact context, and never build a shell string.
Worked example
SELECT * FROM users WHERE name = '" + name + "' becomes a parameterized query with name bound. A user-supplied name of ' OR '1'='1 is then treated as a literal value.