Input Validation and Output Encoding
Implement server-side input validation and context-aware output encoding to neutralize injection and XSS vulnerabilities before they can be exploited.
Why Input Is Dangerous
Every piece of data an application receives from outside — user form inputs, URL parameters, HTTP headers, API request bodies, file uploads — is potentially attacker-controlled. Without validation, attackers inject SQL commands, HTML scripts, shell commands, and XML/LDAP directives into application data flows. Input validation and output encoding are the two core controls that neutralize injection vulnerabilities before they can cause harm.
What Is Input Validation?
Input validation verifies that received data conforms to expected type, format, length, and value range before the application processes it. Validation should be server-side — client-side validation in JavaScript is easily bypassed by attackers who intercept requests with tools like Burp Suite. A username should only accept alphanumeric characters; a date field should only accept valid date formats; an email field should match RFC 5322 syntax.
# Server-side input validation examples:
# Validate username: allow only alphanumeric and underscore
# Pattern: ^[a-zA-Z0-9_]{3,20}$
# Reject: 'admin--', "' OR 1=1--", '<script>alert(1)</script>'
# Validate age: must be integer between 0 and 120
# Reject: -1, 999, 'abc', '18; DROP TABLE users'
# Validate email: match RFC 5322 pattern, max 254 chars
# Reject: 'a@b' (too short), attacker@evil.com<script>...