SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

Input Validation

Never trust what arrives: check and clean every input, to stop injection and bad data.

⏱ 13 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Input validation means never trusting what arrives. Every value that comes from outside your server (forms, URLs, headers, JSON, files) is checked before you use it.

  • Check the type, length, range and format. Say what is allowed (an allow-list), instead of trying to list everything bad.
  • Always validate on the server. Checks in the browser are only for a nicer experience, since an attacker can skip the browser.
  • Validation is the first line of defence. Pair it with parameterized queries and output encoding for injection and XSS.

02Concept: What is it?

Your server cannot control who sends it a request. A real user might type something odd by mistake. A script might send a thousand fields. An attacker might craft a value to trick your database, your file system or another user’s browser. All of it looks like “input”.

So the rule is simple: treat all input as untrusted until it has been checked. If it fails the check, stop right away and answer with a clear error, such as 400 or 422. If it passes, you still need to handle it safely when you use it.

Where validation sits
🌍Untrusted inputforms, JSON, headers, files
→↓check
🛂Validatetype, size, format, allow-list
→↓safe use
🗄️Database, files, pagesparameters, encoding
Reject bad input early. Then handle good input safely, with the right tool for each use.

What to check

🔤Type
A number is a number, a date is a date, a list is a list. Reject anything else.
📏Length and size
Maximum string length, list size, request body size and file size.
🔢Range
An age of -5 or a quantity of 10 million should be refused.
🧩Format
Email, phone, date and ID formats follow a pattern. Check it with a strict rule.
🧠Allow-list beats deny-list
A deny-list says “block these bad things”. Attackers only need one thing you forgot. An allow-list says “only these good things are accepted”, and everything else is refused by default.

03Real-Life Example

🍵The Door Guard at a Party
A guard at a party door has a guest list. Anyone not on the list is turned away, even if they look friendly. That is an allow-list. A worse guard has a “banned people” photo wall. A banned person walks in wearing a hat. The guard also checks that guests are not carrying anything too big for the room (size limits), and that the name on the invitation matches the person (format and type).
Party door
Input validation
The guest list
An allow-list of valid values and formats
The banned photo wall
A deny-list (always has gaps)
Turning someone away at the door
Rejecting early with 400 or 422
A size rule for bags
Length, file size and payload limits
Checking the name on the invitation
Type and format checks
Guards inside the room as well
Parameterized queries and output encoding
Ignoring a friend who vouches “he is fine”
Never trusting client-side checks
Two ways to draw the line
Deny-list
🚫Block: ' ; --
🕳️Everything else gets inincluding what you forgot
Allow-list
✅Accept: a–z 0–9 _ , 3–16 long
🛡️Everything else is refused

04Why Do We Need It?

💉Stops injection
SQL, command and template injection all start with input treated as code.
🕸️Reduces XSS
Validating and encoding stops attacker script from running in other users’ browsers.
🧯Protects the system
Size and rate limits stop huge payloads from eating memory and CPU.
🧼Keeps data clean
Bad values do not get into the database and break reports and jobs later.
💬Better errors
A clear 422 with a reason helps honest users and developers fix the problem.
📜A shared contract
A schema (JSON Schema or OpenAPI) states the rules once for everyone.
Anything that comes from outside is a stranger. Check it at the door, and still handle it carefully inside.

05Where Do We Use It?

📝Forms and sign-up
Usernames, emails, passwords, addresses and comments.
🔌API bodies and query strings
JSON fields, IDs in paths, page numbers and filters.
📎File uploads
File type, size, name and content (do not trust the extension or the declared type).
🧾Headers and cookies
Any header can be forged: Host, User-Agent, custom headers.
📥Messages and webhooks
Events from queues and other systems also need a shape check.
🔗Between your own services
Even internal calls should validate. One bug upstream should not spread.

06Types / Parts / How It Works

Different attacks, different defences

RiskWhat goes wrongThe right defence
SQL injectionInput becomes part of the SQL commandParameterized queries (prepared statements). Validation helps but is not the main fix.
Cross-site scripting (XSS)Input is shown as HTML or script in a pageOutput encoding for the place it appears (HTML, attribute, URL) and a Content Security Policy.
Path traversalInput like ../../ escapes the intended folderDo not build paths from input. Use IDs, and canonicalize and check the final path.
Command injectionInput is passed to a shellAvoid the shell. Use safe APIs with an argument list.
Mass assignmentA client sets fields it should not (isAdmin)Accept only a fixed list of fields and map them yourself.
Resource exhaustionHuge bodies, deep JSON, giant listsLimits on size, depth, count and time, plus rate limiting.
Bad file uploadsA script or huge file is stored and servedCheck size, real content type, store outside the web root, and rename the file.

The same idea in code (illustration)

Glued into text (unsafe) vs parameterized (safe)
// Unsafe: the input becomes part of the command
query("SELECT * FROM users WHERE name = '" + name + "'")

// Safe: the input is sent separately, as data
query("SELECT * FROM users WHERE name = ?", [name])
⚠️Validation is not a replacement for safe handling
An allow-list helps, but names like “O’Brien” are valid and contain a quote. The reliable defence for SQL is always a parameterized query. The reliable defence for XSS is output encoding.
VisualizerAllow-list, deny-list or nothing? And a parameterized queryClick the sample inputs. First try the classic ' OR '1'='1 with no validation and a glued query. Then switch to a deny-list, an allow-list and a parameterized query, and compare what the database returns.
Try a sample
Validation on the server
How the query is built
Accepted (200). Matches the allow-list: 3 to 16 characters from a–z, 0–9 and _.
The command the database receives (toy model)
SELECT name FROM users WHERE name = 'alice_01'
Plain text is just compared with each name.
alice_01bobcarol_kdave99
Verdict
accepted
HTTP 200
Rows returned
1
of 4 users
Data leaked
no
none
Accepted and handled safely. Matches the allow-list: 3 to 16 characters from a–z, 0–9 and _.

A teaching toy. The “database” only understands the classic textbook example and four made-up users, and the rules are simplified. Real systems should use parameterized queries and an allow-list together, and also validate on the server even when the client already checks.

07How to Use It / Steps / Implementation

Validating well, step by step

  1. 1
    Write the rules once
    Describe each field with a schema (JSON Schema, OpenAPI, or your framework’s validators): type, length, range, allowed values and which fields are required.
  2. 2
    Validate on the server, always
    Client-side checks make forms friendlier. They do not protect you. The server must repeat every check.
  3. 3
    Canonicalize first
    Decode and normalise the value (case, Unicode form, URL encoding) before checking it. Otherwise an encoded form can slip past the rule.
  4. 4
    Prefer allow-lists
    List the accepted characters, formats and values. Reject everything else by default.
  5. 5
    Set hard limits
    Limit body size, string length, list size, JSON depth and upload size. Reject early, before the work is done.
  6. 6
    Reject clearly and early
    Return 400 (malformed) or 422 (well-formed but invalid) with a short, safe message. Do not echo raw input or reveal internals.
  7. 7
    Then use input safely
    Parameterized queries for SQL, output encoding for HTML, no shell for commands, and safe file handling. Validation plus safe use together.
💡Validate meaning too
Format checks are not enough. A valid-looking user id may belong to someone else. Always check that the caller is allowed to use that value (authorization), and that business rules hold (stock exists, dates are in order).

08Key Terms to Know

TermMeaning in easy words
Input validationChecking that incoming data is acceptable before using it
SanitizationCleaning or changing input to make it safe. Often less reliable than rejecting it
Allow-listA list of accepted values or patterns. Everything else is refused
Deny-listA list of banned values. Easy to bypass by something unlisted
CanonicalizationTurning input into one standard form before checking it
SQL injectionInput that changes the meaning of a database command
Parameterized queryA query where the input is sent apart from the command, as data
XSSCross-site scripting: attacker script runs in another user’s browser
Output encodingTurning special characters into safe text for where they are shown
Schema validationChecking data against a written description of its shape (JSON Schema, OpenAPI)
Mass assignmentA client setting fields it should not be allowed to set

09Pros, Cons and Trade-offs

✅ Pros
  • Blocks whole classes of attacks early
  • Cleaner data and fewer strange bugs
  • Clear, predictable error messages
  • Rules can be shared as a schema
  • Protects servers from oversized or abusive requests
⚠️ Cons
  • Rules take time to write and keep in step with the product
  • Too strict rules reject real users (names, addresses, other languages)
  • Validation in many places can drift and disagree
  • False sense of safety if you skip safe handling
  • Costs some CPU on every request

Trade-offs

ChoiceWe gainWe lose
Strict allow-listStrong safety, simple to reason aboutReal but unusual values may be refused
Loose rulesFewer rejected usersMore attack surface and bad data
Reject bad inputPredictable, safe behaviourThe user must fix and resend
Silently clean inputFewer errors shown to usersSurprising changes, and sanitizers can be bypassed
Validate at the edge onlyOne place, simpleInternal bugs and other callers can still send bad data
Validate in every layerDefence in depthDuplicate rules and more upkeep

10Common Problems and Mistakes

Common mistakes

  1. Only checking in the browser. Anyone can call your API directly.
  2. Relying on a deny-list. There is always one more trick you did not list.
  3. Building SQL by joining strings, then trying to fix it with “escape the quotes”.
  4. Trusting the file extension or Content-Type of an upload.
  5. Checking before decoding. A value looks fine, then gets decoded into something else.
  6. Over-strict rules (for example forbidding apostrophes or non-English letters in names), which block real people.
  7. Echoing raw input in error messages, which can leak data or enable XSS.

Things to watch

🌍Unicode
Names and text come in many scripts. Normalise, and think about look-alike characters.
🧮Regex cost
A badly written pattern can take very long on crafted input (ReDoS). Keep patterns simple and set limits.
📦Nested data
Deep or huge JSON can use a lot of memory. Limit depth and size.
🔁Many entry points
APIs, queues, files and admin tools all need the same care. Share the validation code.

11Real-World Examples

📘OWASP guidance
Injection and broken input handling have been on the well-known web risk lists for years.
🧩Schema libraries
Tools such as JSON Schema validators, Zod, Pydantic and Bean Validation check data against a described shape.
🚪API gateways
Gateways can reject requests that break the OpenAPI schema before they reach your service.
🧱Web application firewalls
A WAF adds a rough filter in front, as one extra layer. It does not replace validation in your code.
☁️Cloud upload services
Object stores use signed upload URLs with size and type conditions.
🛍️Shops and forms
Quantity, price and address checks happen on the server, whatever the page shows.
📝Note
Library names and features change over time. Pick a maintained validation library for your language and keep it updated.
Mini case: a sign-up request through three gates
🚪Gatewaysize + schema
→↓ok
🛂Servicefield rules + business rules
→↓ok
🗄️Databaseparameters + constraints
Edge Service Storage
Each gate catches different problems. None of them replaces the others.

12Related Topics to Read Next

CSRF→

Another core web defence, aimed at forged requests.

Error Handling and Status Codes→

How to say 400 and 422 clearly when input is rejected.

OpenAPI / Swagger→

A schema that can describe and enforce the rules.

Rate Limiting→

Limits how much bad or heavy input a caller can send.

Bulk APIs and File Upload→

Uploads and large batches need extra limits and checks.

API Gateway Pattern→

A gateway can do the first round of validation at the edge.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Rule: all outside input is untrusted until checked.
  • ✔Where: on the server, always. Client checks are for comfort.
  • ✔Check: type, length, range, format, required fields, and sizes.
  • ✔Style: allow-list over deny-list. Refuse by default.
  • ✔SQL: parameterized queries. HTML: output encoding.
  • ✔Errors: reject early with 400 or 422, a short safe message.
  • ✔Limits: body size, depth, list size, upload size, and rate.
  • ✔One line: “Check it at the door, and handle it safely inside.”
← Previous
CSRF
Next →
mTLS and Request Signing (HMAC)