Preparing your workspace
Validation checks whether input is acceptable, while context-aware output encoding prevents data from being interpreted as executable content.
All client-provided data should be treated as untrusted. Validation should check type, length, format, allowed values, and business rules. Output encoding depends on where data will be placed, such as HTML, an HTML attribute, a URL, JavaScript, or SQL. Database parameterization protects SQL structure, while HTML escaping protects HTML contexts. Security comes from using the correct defense for the correct output context rather than trying to sanitize everything with one generic function.
A profile name should be validated for length and then safely encoded before being displayed in an HTML page.
const name = String(input.name ?? '').trim();
if (name.length === 0 || name.length > 100) {
throw new Error('Invalid name');
}
const safeHtml = escapeHtml(name);The input is validated and then encoded before being placed into HTML.