What if a tiny unchecked input could crash your whole app or open a hacker's door?
Why Input validation and sanitization in Node.js? - Purpose & Use Cases
Imagine building a web form where users type their names and emails. You try to accept the input as-is and store it directly in your database.
Without checking or cleaning the input, users might enter wrong or harmful data. This can cause your app to crash, show wrong info, or even let hackers break in.
Input validation and sanitization automatically check and clean user data before using it. This keeps your app safe, stable, and working as expected.
const name = req.body.name; // no checks saveToDb(name);
const name = sanitize(req.body.name);
if (validate(name)) saveToDb(name);This lets you trust user input and protect your app from errors and attacks.
When signing up for a newsletter, validation ensures emails look real, and sanitization removes harmful code from comments.
Manual input handling risks errors and security issues.
Validation checks data fits expected rules.
Sanitization cleans data to remove harmful parts.
Practice
Solution
Step 1: Understand input validation
Input validation ensures that the data received from users meets expected rules and is safe to use.Step 2: Identify the purpose in Node.js
In Node.js, input validation prevents bad or harmful data from causing errors or security issues.Final Answer:
To check if the input data is correct and safe before processing -> Option AQuick Check:
Input validation = check data safety [OK]
- Confusing validation with data storage
- Thinking validation formats output
- Assuming validation improves speed
Solution
Step 1: Identify modern import syntax
Node.js with ES modules usesimport { check } from 'express-validator';to import named exports.Step 2: Check other options
const { check } = require('express-validator'); uses CommonJS require but destructuring is possible only if CommonJS is used; import check from 'express-validator'; imports default which express-validator does not export; const check = require('express-validator/check'); uses a wrong path.Final Answer:
import { check } from 'express-validator'; -> Option DQuick Check:
Use ES module import for express-validator [OK]
- Using require instead of import in ES modules
- Importing default instead of named export
- Using incorrect module paths
app.post('/submit', [
check('email').isEmail(),
check('age').isInt({ min: 18 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Data is valid');
});What will be the response if the user sends
{ "email": "userexample.com", "age": 17 }?Solution
Step 1: Analyze validation rules
The code checks if 'email' is a valid email and 'age' is an integer >= 18.Step 2: Check input values
The email 'userexample.com' is missing '@', so invalid. Age 17 is less than 18, so invalid.Final Answer:
Status 400 with errors about invalid email and age -> Option BQuick Check:
Invalid email and age cause 400 error [OK]
- Assuming invalid data passes validation
- Confusing status codes
- Ignoring validationResult usage
app.post('/data', [
check('username').trim().escape()
], (req, res) => {
// ...
});What is the likely reason the spaces are not removed?
Solution
Step 1: Understand trim() behavior
The trim() method removes whitespace only from the start and end of a string, not inside it.Step 2: Check escape() effect
escape() converts special characters but does not remove spaces inside the string.Final Answer:
The trim() method removes spaces only from start and end, not inside the string -> Option CQuick Check:
trim() trims edges, not inner spaces [OK]
- Expecting trim() to remove all spaces
- Misunderstanding escape() purpose
- Thinking check() lacks trim() support
Solution
Step 1: Validate username and email correctly
Username must be alphanumeric and trimmed, so trim() before or after is okay but isAlphanumeric() must check the trimmed string. Email must be checked with isEmail() and normalized with normalizeEmail().Step 2: Analyze options
[ check('username').trim().isAlphanumeric(), check('email').normalizeEmail().isEmail() ] applies trim() before isAlphanumeric() which ensures validation on trimmed string; [ check('username').isAlphanumeric().trim(), check('email').isEmail().normalizeEmail() ] applies isAlphanumeric() before trim(), which may validate untrimmed input; also, normalizeEmail() should come before isEmail() to validate normalized email; [ check('username').escape().isAlphanumeric(), check('email').isEmail().trim() ] escapes username unnecessarily and trims email which is not needed; [ check('username').isAlphanumeric().escape(), check('email').trim().normalizeEmail() ] escapes username and trims email incorrectly.Final Answer:
[ check('username').trim().isAlphanumeric(), check('email').normalizeEmail().isEmail() ] -> Option AQuick Check:
Trim before validation for username; normalize before validation for email [OK]
- Applying sanitization after validation incorrectly
- Using escape() unnecessarily
- Trimming email instead of normalizing
Ready to prove it?
Pass the test and this pattern moves unknown
