Sanitizing vs. Validating

Difficulty: Beginner

Question

What is the difference between input validation and input sanitization, and when should you use each?

Answer

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.

Validation: decide yes or no

Good validation is allowlist based: define what is allowed and reject everything else.

  • Type and format: pincode is exactly 6 digits, amount is a positive integer in paise, email matches a sane pattern.
  • Range and length: rating is 1 to 5, name is at most 100 characters.
  • Business rules: a coupon is not expired, a delivery slot is in the future.
  • Enum values: 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: transform to safe

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.

Encoding is the third, often forgotten piece

TechniqueQuestion it answersExample
ValidationIs this input acceptable?Reject age=-5 with 400
SanitizationCan I make this input safe to keep?DOMPurify strips <img onerror>
Output encodingIs it safe in this output context?< becomes &lt; 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:

  • Use parameterized queries or an ORM for SQL, not escaping.
  • Let your template engine or React auto-escape HTML ({value} in JSX is escaped; dangerouslySetInnerHTML is not).
  • Encode for the specific context at the point of output.

Common mistakes

  • Relying on sanitization to stop SQL injection. Parameterize instead.
  • Sanitizing then storing, then later rendering in a different context where it is unsafe again.
  • Blocklisting "bad" characters, which always misses something and breaks legitimate names like O'Brien.
  • Silently mutating input users did not expect (for example, removing characters from a password). Reject with a clear message instead.
Where each defence applies. Validation guards the door, sanitization handles rich content, and encoding protects every output.
  1. Raw request input: Never trusted, even from your own frontend.
  2. Normalize: Trim, lowercase email, Unicode NFC.
  3. Validate against schema: Reject with 400 if it does not match.
  4. Sanitize rich HTML only: Allowlist tags with DOMPurify.
  5. Encode at output: Parameterized SQL, auto-escaped HTML.

Code examples

Validating an order request with Zod

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.

Sanitizing user HTML with DOMPurify

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.

Key points

  • Validation rejects bad input; sanitization transforms input to make it safe
  • Prefer allowlists over blocklists for both
  • Always validate on the server; client checks are only for UX
  • Sanitize only when accepting rich content such as HTML, using a proven library
  • Output encoding and parameterized queries are the primary injection defences

Common follow-up questions

  • Why is escaping SQL input worse than using parameterized queries?
  • How does React protect against XSS by default and where does that protection stop?
  • Should you sanitize data before storing it or before rendering it?
  • What is the difference between a blocklist and an allowlist approach?

Interview tips

  • Bring up output encoding as the third concept; most candidates stop at validation vs sanitization
  • Give a concrete schema example with real fields rather than talking abstractly
  • Avoid suggesting regex-based script stripping; name DOMPurify or a similar library

Concepts covered

Input Validation, Sanitization, Output Encoding, Allowlist, Schema Validation

More Web Security (OWASP, JWT, XSS, CSRF) questions