How does input validation differ from output encoding?
Model answer
Input validation checks that data is acceptable when it enters the system: type, length, range, format and business rules. Output encoding transforms data when it leaves, so the receiver treats it as plain data and not as code.
Validation is best done as an allow-list at the edge: an age is an integer from 0 to 150, a country is one of a known set, a username matches ^[a-z0-9_]{3,20}$. Reject early with a clear error. It reduces the attack surface and keeps data clean, but it cannot be the only defense, because some valid input, such as a name like O'Brien or a comment containing <b>, is dangerous in the wrong place.
Encoding depends on the destination: HTML escaping for HTML, parameter binding for SQL, shell-argument arrays for commands, URL encoding for URLs. The same string needs different treatment in each.
Typical pairing: validate on input, encode on output, using the framework's defaults such as template auto-escaping.
Takeaway: validation narrows what comes in; encoding makes whatever comes out safe for its context.
Key points
- Validation checks data on the way in
- Encoding makes data safe on the way out
- Prefer allow-lists to block-lists
- Encoding must match the output context
Likely follow-ups
- Why is a blocklist of bad characters weak?
- Where do you validate: client, API gateway or service?
Common mistakes
- Believing validated input is safe to place anywhere
- Encoding once at input instead of at each output