Validation Checks Rules; Sanitization Cleans Input
Validation checks if input fits your rules and rejects failures. Sanitization cleans allowed input so it cannot cause harm. Validate at the boundary to enforce shape, then sanitize before rendering. Never swap them; scrubbing a bad date does not make it valid.
Why it exists
Every HTTP request carries untrusted data. If your Express application assumes that req.body fields are the correct type, safe length, or benign content, attackers can inject scripts, overflow buffers, or corrupt business logic. Validation and sanitization are two separate lines of defense invented to solve different parts of this problem. Validation ensures the data belongs in your domain, while sanitization ensures that data which is allowed in cannot weaponize the systems it touches.
The mental model
Imagine a hospital emergency room. Validation is triage: a nurse checks your symptoms, temperature, and ID, and turns you away if you do not need emergency care. Sanitization is the hand-washing station: everyone who enters scrubs in so they do not introduce infection. Triage does not clean you, and hand-washing does not decide whether you belong. Both happen, and the order matters. You triage first, then scrub.
How it works
Validation enforces contracts. In Express, this means checking that a userId param is a UUID, that an age query is an integer between zero and one hundred twenty, or that a required string is present and within length limits. If the check fails, you return a four-hundred response and halt. Sanitization transforms content. For a comment field that passes validation, you escape HTML entities, strip script tags with a library like DOMPurify, or trim whitespace. The goal is not to reject the input but to remove or neutralize payloads that would change behavior in a browser, database, or shell.
When to use it
Use validation at every trust boundary where shape and type matter. Check req.body, req.query, and req.params before they reach controllers, services, or ORM calls. Use sanitization when you must accept rich or free-form text that will later be rendered in HTML, embedded in JSON sent to another service, or logged. Any output context that interprets special characters is a candidate for sanitization.
When not to use it
Do not sanitize as a replacement for validation. Removing dangerous characters from a malformed ISO date string leaves you with a still-invalid date that may crash your parser. Do not validate as a replacement for output escaping. Rejecting strings that contain angle brackets at the door does not protect you when another code path renders unsanitized data from the database. Also, avoid sanitizing before validating, because altering input can mask errors and produce values that sneak past your rules.
One canonical example
Consider an Express endpoint that accepts a public user bio. Validation confirms the payload is a string between one and five hundred characters and rejects objects, arrays, or booleans. Sanitization then escapes any HTML tags so that a user submitting a bold tag sees literal angle brackets in the browser instead of triggering script execution. If you only validated length, you would store a cross-site scripting payload. If you only sanitized without type checks, a nested object might bypass your ORM and hit the database with an invalid schema.
Interview question
An Express endpoint accepts a public user bio. Which outcome shows validation alone working as intended?
- a.A bio submitted as a JSON array is rejected with a 400 response.Correct
- b.A bio with leading whitespace is trimmed and then accepted.
- c.A bio longer than 500 characters is truncated before storage.
- d.A bio containing angle brackets is stored after being escaped to HTML entities.
Why? this is the answer
Validation enforces type and shape, so it rejects an array with a 400 error. Truncating or trimming input alters the data, which is sanitization or transformation, not validation.
Just read this? Test yourself on what you have been reading.
- #express
- #security
- #input-handling
- #nodejs
- #middleware
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on express — each one lists the topics its interview covers.
See open roles