Secure Input Validation
TL;DR: Never trust data coming from outside your system. Validate the type and shape, sanitize the content, and always do it on the server, not just the client.
Every input field in your app is a door. Most of the time, friendly users walk through it. But some users will try to push through something your app wasn’t designed to handle: a script tag, an absurdly long string, a SQL fragment disguised as a username.
The fix isn’t complicated. You just have to stop treating input as trustworthy by default.
There are two distinct steps here that developers often blur together. Validation checks whether the input is the right shape: is it a string? Is it under 255 characters? Is it a valid email format? Sanitization strips or escapes anything dangerous that got through: HTML tags, special characters, SQL metacharacters.
Do both. Do them on the server. Client-side validation is helpful for UX, but anyone can open DevTools and bypass it in 10 seconds.
Whitelisting beats blacklisting. Instead of trying to block every bad character you can think of, define exactly what you will accept and reject everything else. Your list of dangerous inputs will always be incomplete. Your list of acceptable inputs won’t be.
function validateInput(input) {
if (typeof input !== 'string' || input.length > 255) {
throw new Error('Invalid input');
}
return input.replace(/[<>'"]/g, '');
}
A simple function like this catches a lot. For anything more serious, use a well-maintained library rather than rolling your own sanitizer.
Further reading: OWASP Input Validation Cheat Sheet