Problem
You need to validate incoming JSON data in POST requests to ensure required fields exist, have correct types, and meet specific criteria before processing.
Solution
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
// Validation middleware
const validateUser = [
body('email')
.isEmail()
.withMessage('Must be a valid email')
.normalizeEmail(),
body('password')
.isLength({ min: 6 })
.withMessage('Password must be at least 6 characters'),
body('age')
.isInt({ min: 18, max: 100 })
.withMessage('Age must be between 18 and 100')
];
// Route with validation
app.post('/api/users', validateUser, (req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
// Process valid data
const { email, password, age } = req.body;
res.json({
success: true,
message: 'User created successfully',
user: { email, age }
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Install express-validator:
npm install express-validator
Explanation
express-validator
provides middleware functions that validate request data. Each body()
call validates a specific field with built-in validators like isEmail()
, isLength()
, and isInt()
.
validationResult(req)
collects all validation errors. If errors exist, return a 400 status with error details. The validation runs before your route handler, so you always receive clean, validated data when validation passes.
Top comments (0)