Input Validation and Sanitization
Input validation and sanitization are used to make sure user-provided data is safe, expected, and controlled before the application uses it.
In frontend applications, user input can come from:
- forms
- search boxes
- query parameters
- uploaded files
- images
- API responses
- third-party libraries
The main idea is simple:
Never trust raw input.
Validate it first.
Sanitize it before using it.
Handle errors safely.
What It Is
Input validation means checking whether the input matches the expected rules.
Example:
Expected: number
Received: "abc"
Result: invalid
Sanitization means cleaning or escaping input so it cannot create security issues when used in the application.
Example:
Raw input: <script>alert("xss")</script>
Sanitized input: safe escaped text
Simple difference:
| Concept | Meaning |
|---|---|
| Validation | Checks whether input is allowed |
| Sanitization | Cleans input before usage |
| Error handling | Handles invalid input safely |
Why It Matters
User input can become dangerous if it is directly trusted.
Bad input handling can cause:
| Problem | Example |
|---|---|
| Broken application flow | Wrong data type passed to logic |
| Security attacks | Unsafe script or query parameter usage |
| Server overload | Huge data sent through input fields |
| File upload risk | Wrong file type or large file uploaded |
| Data corruption | Invalid values saved in the system |
The PDF also mentions that huge data can be used in attacks like DDoS. If the application does not check input size, it can affect server stability.
Core Flow
A safe input handling flow looks like this:
Receive user input
↓
Validate allowed fields and values
↓
Check type, length, and size
↓
Escape or sanitize unsafe characters
↓
Handle errors properly
↓
Send safe data to server/API
Main Security Goals
Input validation and sanitization mainly focus on:
| Goal | Meaning |
|---|---|
| Accept only expected input | Do not allow random keys or values |
| Prevent unsafe execution | Escape user input before rendering or using it |
| Protect API calls | Handle query params and URLs safely |
| Reduce server load | Limit input size and file size |
| Avoid weak dependencies | Do not use third-party libraries for every small task |
| Keep security updated | Update libraries and patches regularly |
Use Framework and Library Support
Frameworks and libraries like React and Axios already help with some basic safety at their own level.
For example:
- React escapes rendered text by default in normal JSX usage.
- Axios helps structure API requests properly.
But this does not mean the application is fully secure automatically.
Framework support is helpful
↓
But developer validation is still required
You should still validate:
- what values are allowed
- what keys are accepted
- what data type is expected
- how large the input can be
- whether uploaded files are safe
Whitelist Validation
Whitelist validation means defining what is allowed and rejecting everything else.
Instead of thinking:
What should I block?
Think:
What should I allow?
Example:
const allowedRoles = ["admin", "user", "viewer"];
function isValidRole(role) {
return allowedRoles.includes(role);
}
If the value is not in the allowed list, reject it.
This is useful for fields like:
- role
- status
- category
- sort order
- filter type
- payment mode
Regular Expressions
Regular expressions are useful when input must follow a specific pattern.
Example:
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
Flow:
User enters input
↓
Input is checked against regex
↓
Valid pattern -> accept
Invalid pattern -> show error
Use regular expressions for inputs like:
- phone number
- username
- postal code
- ID format
Escape User Input
Escaping user input means converting unsafe characters into safe text before displaying or using them.
This is important when user input may contain HTML-like characters.
Example:
function escapeInput(value) {
return value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
Mental model:
Raw user input should not directly become executable HTML.
Parameterized URLs
The PDF mentions that parameterized URLs need special care because applications may use query parameters to perform some action.
Example URL:
/products?category=mobile&sort=price
The values from query params should be validated before use.
Example:
const allowedSortValues = ["price", "rating", "latest"];
function getSafeSortValue(sortValue) {
if (allowedSortValues.includes(sortValue)) {
return sortValue;
}
return "latest";
}
Also, when creating URLs, encode dynamic values:
const searchText = "red shoes";
const url = `/search?q=${encodeURIComponent(searchText)}`;
This prevents unsafe or broken URL construction.
Validate Data Types Always
Always check whether the input is the expected type.
Example:
function validateAge(age) {
const numericAge = Number(age);
if (Number.isNaN(numericAge)) {
return false;
}
return numericAge >= 0;
}
Common checks:
| Expected Type | Validation Example |
|---|---|
| Number | Number.isNaN(Number(value)) === false |
| String | typeof value === "string" |
| Boolean | typeof value === "boolean" |
| Array | Array.isArray(value) |
| Object | value is not null and not array |
This prevents wrong input from breaking business logic.
Length and Size Check
Input length and size must always be verified.
Example:
function isValidComment(comment) {
return typeof comment === "string" && comment.length <= 500;
}
Why it matters:
Small expected input
↓
Huge unexpected data submitted
↓
Application/server may slow down or fail
The PDF gives a real-world example: if huge data is not handled properly, it can become a DDoS-related risk and bring down the server.
File and Image Validation
For files and images, validate both type and size.
Important checks:
- file extension
- file type
- file size
- image size if needed
Example:
function validateImage(file) {
const allowedTypes = ["image/png", "image/jpeg"];
const maxSizeInMB = 2;
const maxSizeInBytes = maxSizeInMB * 1024 * 1024;
if (!allowedTypes.includes(file.type)) {
return false;
}
if (file.size > maxSizeInBytes) {
return false;
}
return true;
}
Simple mental model:
Do not allow any file just because the user selected it.
Check type, extension, and size.
Client Side Validation
Client-side validation improves user experience and catches invalid input early.
But the PDF clearly mentions that we should not depend only on server-side validation.
Frontend validation helps by:
- showing quick errors
- avoiding unnecessary API calls
- blocking obviously invalid input
- reducing accidental bad requests
Example:
function validateUsername(username) {
if (!username) return "Username is required";
if (username.length < 3) return "Username must be at least 3 characters";
if (username.length > 20) return "Username must be less than 20 characters";
return null;
}
Important:
Client-side validation is useful,
but backend validation is still required.
Error Handling
Proper error handling is important, especially global exception handling.
Bad error handling can:
- expose internal details
- confuse users
- hide real security issues
- make debugging harder
Example:
try {
await submitForm(data);
} catch (error) {
console.error("Form submission failed:", error);
showToast("Something went wrong. Please try again.");
}
Simple rule:
Log useful details for developers.
Show safe and simple messages to users.
Security Headers
The PDF mentions that security headers should never be avoided.
Security headers help protect the application at the browser level.
They can help reduce risks related to:
- unsafe scripts
- clickjacking
- content sniffing
- insecure communication
- unwanted browser behavior
Mental model:
Input validation protects data.
Security headers add browser-level protection.
Both are needed.
Regular Updates and Patches
Security-related fixes are constantly pushed in libraries and frameworks.
That is why dependencies should be updated when security patches are available.
Important points:
- do not ignore security updates
- patch libraries regularly
- update when the change is security-related
- avoid using outdated packages
Simple flow:
Library vulnerability found
↓
Security patch released
↓
Project dependency updated
↓
Risk reduced
Security Audits and Testing
Security audits and testing should be done regularly.
They help find problems in:
- input handling
- dependency usage
- validation rules
- third-party libraries
- security headers
- application behavior
Simple meaning:
Do not assume input handling is safe.
Test and audit it.
Third-Party Library Usage
The PDF warns that third-party libraries should not be used for everything.
Reason:
Every extra library can add security risk.
Use third-party libraries when:
- the problem is complex
- the library is maintained
- the library is trusted
- the benefit is worth the dependency risk
Avoid third-party libraries for very small tasks that can be written safely in a few lines.
Example:
Small formatting helper -> write yourself
Complex validation/security tool -> use trusted library if needed
Basic Checklist
Use this checklist while handling input:
- Use framework and library protections, but do not depend only on them.
- Validate allowed keys and values using whitelist validation.
- Use regular expressions for strict input formats.
- Escape user input before displaying or using it in unsafe places.
- Validate query parameters before using them.
- Encode dynamic values while creating URLs.
- Always validate data types.
- Check input length and size.
- Validate file/image type, extension, and size.
- Add client-side validation for better user experience.
- Keep backend validation as the final protection layer.
- Add proper global error handling.
- Do not ignore security headers.
- Regularly update and patch libraries.
- Perform security audits and testing.
- Avoid third-party libraries for small/simple tasks.
Interview Style Answer
Input validation and sanitization are important security practices for handling user-provided data. Validation checks whether the input matches expected rules, such as allowed values, correct data type, correct format, and maximum size. Sanitization cleans or escapes unsafe input before using or rendering it.
In frontend applications, we should use framework support from tools like React and Axios, but we should not fully depend on them. We should apply whitelist validation, regular expressions, query parameter validation, URL encoding, type checks, length checks, and file validation. We should also handle errors properly, keep libraries updated, use security headers, run audits, and avoid unnecessary third-party libraries.
One-Line Summary
Input validation and sanitization mean accepting only safe, expected input and cleaning unsafe data before using it in the application.
Final Mental Model
Validate -> Sanitize -> Limit -> Handle Errors -> Patch -> Audit
Or remember it like this:
Validate what is allowed
Escape what is unsafe
Limit what is too large
Check files before upload
Handle errors safely
Keep libraries updated
Avoid unnecessary dependencies