Input Validation & Sanitization
The practice of verifying and cleaning all user-supplied data before processing to prevent injection attacks and data corruption.
Description
Input validation and sanitization form the first line of defense against a wide range of security vulnerabilities. Validation checks whether input conforms to expected formats, types, lengths, and ranges, rejecting anything that doesn't meet criteria. Sanitization transforms input to remove or encode potentially dangerous characters. Together, they prevent SQL injection, XSS, command injection, path traversal, and many other attack vectors.
Effective input validation follows the allowlist (whitelist) approach: defining exactly what is permitted rather than trying to block known-bad patterns (denylist). This is because denylists are inherently incomplete -- attackers constantly discover new bypass techniques. Validation should occur on both the client side (for user experience) and the server side (for security), with server-side validation being the authoritative check that cannot be bypassed.
Modern applications benefit from schema validation libraries like Zod, Yup, or Joi that provide declarative, composable validation schemas. These enforce type safety, string patterns, numeric ranges, array lengths, and custom constraints. Sanitization libraries like DOMPurify handle HTML content, while purpose-built validators handle email addresses, URLs, phone numbers, and other structured formats. Every API endpoint, form handler, and data import pathway should validate inputs before any processing occurs.
Prompt Snippet
Validate all inputs server-side using schema validation libraries (Zod, Joi, or Yup) at the API boundary before any business logic executes. Define strict schemas with explicit types, string length limits (.max()), regex patterns (.regex()), and enum constraints. Sanitize HTML content with DOMPurify configured with ALLOWED_TAGS and ALLOWED_ATTR restrictive allowlists. For numeric inputs, validate ranges and reject NaN/Infinity. Implement validation middleware (e.g., express-validator or a Zod-based middleware) that returns 400 with structured error messages, never echoing raw input back in error responses to prevent reflected XSS.
Tags
Related Terms
XSS (Cross-Site Scripting) Prevention
Techniques to prevent attackers from injecting malicious scripts into web pages viewed by other users.
SQL Injection Prevention
Techniques to prevent attackers from inserting malicious SQL statements into application queries.
Path Traversal Prevention
Preventing attackers from accessing files and directories outside the intended scope by manipulating file path inputs.
Output Encoding
The process of converting untrusted data into a safe representation before rendering it in a specific output context.