Input Validation vs Output Encoding
People think checking what users type stops cross-site scripting, and it does not. Input validation turns away data with the wrong shape as it comes in. But a comment box has to take almost any text. Output encoding works on the way out. It turns signs like the less-than sign into safe codes, so the browser shows the text and never runs it. You want both.
Input Validation
Making sure what users send fits the rules. Then your code uses it.
Input validation checks outside data against rules before your code uses it. An age should be a whole number between 0 and 150. An email should look like an email. Anything that breaks the rules is turned away with a clear message. Checks in the browser are only for comfort; the server must check again, because anyone can skip the page.
Output Encoding
Turning signs like < into safe codes. Then user text can go on a page.
Output encoding changes special characters before user text is put on a page. In HTML, < becomes < and > becomes >. The browser then shows the text instead of running it as code. Each place needs its own rules, so HTML, links and scripts are each encoded their own way. It is the main defence against cross-site scripting.
In one line
- Input Validation
- Making sure what users send fits the rules. Then your code uses it.
- Output Encoding
- Turning signs like < into safe codes. Then user text can go on a page.