Difficulty: Beginner
What is the difference between input validation and input sanitization, and when should you use each?
Validation checks whether input matches what you expect and rejects it if it does not, for example "is this a valid email" or "is quantity an integer between 1 and 10". Sanitization changes the input to make it safe, for example stripping disallowed HTML tags or trimming whitespace. Validate first and reject bad data; sanitize only when you must accept rich content; and remember that the real defence against injection is context-aware output encoding and parameterized queries.
Good validation is allowlist based: define what is allowed and reject everything else.
pincode is exactly 6 digits, amount is a positive integer in paise, email matches a sane pattern.rating is 1 to 5, name is at most 100 characters.status is one of placed, shipped, delivered.Always validate on the server. Client-side validation is a UX nicety; anyone can call your API with curl and skip it. Libraries like Zod, Joi, Pydantic or Bean Validation let you declare a schema once and get both checks and clear error messages.
Sanitization is needed when you intentionally accept content that could be dangerous, most commonly user-written HTML in a blog editor, product review or chat message. You cannot reject all HTML, so you parse it and keep only an allowlist of safe tags and attributes. Use a maintained library such as DOMPurify (browser or Node with jsdom) or sanitize-html, never a hand-written regex like replace(/<script>/g, ''), which is trivially bypassed with <ScRipt>, <img onerror=...> or <svg onload=...>.
Normalization is a gentle form of sanitization: trimming, lowercasing emails, Unicode NFC normalization. Do it before validation so the checks run on the canonical value.
| Technique | Question it answers | Example |
|---|---|---|
| Validation | Is this input acceptable? | Reject age=-5 with 400 |
| Sanitization | Can I make this input safe to keep? | DOMPurify strips <img onerror> |
| Output encoding | Is it safe in this output context? | < becomes < in HTML |
The same string can be safe in one context and dangerous in another: HTML body, an HTML attribute, a JavaScript string, a URL, and SQL all need different handling. So instead of trying to "clean" input for every possible use:
{value} in JSX is escaped; dangerouslySetInnerHTML is not).import { z } from 'zod';
const OrderSchema = z.object({
email: z.string().trim().toLowerCase().email(),
pincode: z.string().regex(/^[1-9][0-9]{5}$/, 'Invalid pincode'),
amountPaise: z.number().int().positive().max(10_000_000),
paymentMode: z.enum(['UPI', 'CARD', 'COD']),
});
app.post('/orders', (req, res) => {
const parsed = OrderSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.flatten() });
}
// parsed.data is typed and trusted to match the schema
createOrder(parsed.data);
res.status(201).end();
});
The schema is an allowlist: unknown payment modes, fractional paise or bad pincodes are rejected before any business logic runs.
import DOMPurify from 'dompurify';
const dirty = '<p>Great food!</p><img src=x onerror=alert(1)><script>steal()</script>';
const clean = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['p', 'b', 'i', 'a', 'ul', 'li'],
ALLOWED_ATTR: ['href'],
});
console.log(clean);
DOMPurify parses the HTML like a browser would and keeps only allowlisted tags and attributes, which a regex cannot do reliably.
Input Validation, Sanitization, Output Encoding, Allowlist, Schema Validation