Request validation helps check if the data sent to your server is correct and safe before using it.
Request validation in Node.js
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); app.post('/route', [ body('fieldName').validationMethod(), // more validations ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // handle valid data res.send('Success'); });
Use express-validator package to add validation rules easily.
Always check validationResult to find errors before processing data.
body('email').isEmail()body('age').isInt({ min: 18 })
body('password').isLength({ min: 6 })
body('username').notEmpty()This code creates a simple server that checks if the username is not empty, the email is valid, and the password is at least 6 characters long before accepting the registration.
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); app.post('/register', [ body('username').notEmpty(), body('email').isEmail(), body('password').isLength({ min: 6 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.send('User registered successfully'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always validate user input to avoid crashes and security issues.
Use clear error messages to help users fix their input.
Validation runs before your main code, so bad data never reaches your logic.
Request validation checks data before using it.
Use express-validator for easy rules in Node.js.
Always handle validation errors to keep your app safe and stable.
Practice
Solution
Step 1: Understand request validation
Request validation means checking the data sent by users before the app uses it.Step 2: Identify the main goal
The goal is to ensure data is safe and correct to avoid errors or security issues.Final Answer:
To check incoming data before using it -> Option CQuick Check:
Request validation = check data first [OK]
- Thinking validation speeds up server
- Confusing validation with data storage
- Assuming validation creates routes
Solution
Step 1: Recall express-validator syntax
express-validator uses check('fieldName').validationMethod() to validate fields.Step 2: Match correct method for email
The method is isEmail() to check if the input is a valid email.Final Answer:
check('email').isEmail() -> Option DQuick Check:
express-validator uses check() + isEmail() [OK]
- Using validate() instead of check()
- Wrong method names like validateEmail()
- Mixing method order or names
app.post('/signup', [
check('email').isEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Success');
}
]);Solution
Step 1: Check validation rule
The rule check('email').isEmail() requires a valid email format.Step 2: Analyze input and error handling
The input 'not-an-email' fails isEmail(), so errors.isEmpty() is false, triggering status 400 with error details.Final Answer:
Response with status 400 and error details -> Option AQuick Check:
Invalid email triggers 400 error [OK]
- Assuming success response on invalid input
- Expecting server crash on validation fail
- Ignoring error handling logic
app.post('/login', [
check('password').isLength({ min: 6 }),
(req, res) => {
const errors = validationResult;
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.send('Logged in');
}
]);Solution
Step 1: Check usage of validationResult
validationResult must be called as validationResult(req) to get errors from the request.Step 2: Identify the mistake in code
The code assigns errors = validationResult without calling it, so errors is not an object with isEmpty().Final Answer:
validationResult is not called with req, so errors is not an object with isEmpty() -> Option AQuick Check:
Call validationResult(req) to get errors [OK]
- Forgetting to call validationResult as a function
- Using wrong validation method names
- Confusing middleware flow with next()
Solution
Step 1: Validate 'username' requirements
Username is required and must have at least 3 characters, so use notEmpty() and isLength({ min: 3 }).Step 2: Validate 'age' requirements
Age is optional but if present must be numeric, so use optional() and isNumeric().Final Answer:
[check('username').isLength({ min: 3 }).notEmpty(), check('age').optional().isNumeric()] -> Option BQuick Check:
Required username + optional numeric age = [check('username').isLength({ min: 3 }).notEmpty(), check('age').optional().isNumeric()] [OK]
- Marking required fields as optional
- Not chaining optional() before other checks
- Using wrong validators like isString() for numbers
Ready to prove it?
Pass the test and this pattern moves unknown
