JAVASCRIPT
Robust Server-Side Input Validation with Express-Validator
Implement comprehensive server-side input validation for API endpoints in Node.js Express using `express-validator` to prevent malicious data and ensure data integrity.
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json()); // For parsing application/json
app.post(
'/register',
[
// Validation chain for 'username'
body('username')
.isLength({ min: 3 }).withMessage('Username must be at least 3 characters long')
.trim()
.escape(), // Sanitize input
// Validation chain for 'email'
body('email')
.isEmail().withMessage('Invalid email address')
.normalizeEmail(), // Sanitize input
// Validation chain for 'password'
body('password')
.isLength({ min: 8 }).withMessage('Password must be at least 8 characters long')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])/) // Requires a specific set of chars
.withMessage('Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character'),
// Validation chain for 'age' (optional, but must be numeric if present)
body('age')
.optional()
.isInt({ min: 18 }).withMessage('Must be an integer and at least 18 years old')
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// If validation passes, process the sanitized data
const { username, email, password, age } = req.body;
console.log('Received valid user data:', { username, email, age });
// In a real app, you would hash the password and save the user
res.status(200).json({ message: 'User registered successfully!', data: { username, email, age } });
}
);
app.listen(3000, () => console.log('Server running on port 3000'));
// Example cURL requests:
// Valid:
// curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser", "email":"[email protected]", "password":"StrongPassword123!", "age":25}' http://localhost:3000/register
// Invalid (short username):
// curl -X POST -H "Content-Type: application/json" -d '{"username":"tu", "email":"[email protected]", "password":"StrongPassword123!"}' http://localhost:3000/register
// Invalid (weak password):
// curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser", "email":"[email protected]", "password":"weak", "age":25}' http://localhost:3000/register
How it works: This Node.js Express snippet demonstrates robust server-side input validation using the `express-validator` library. It defines an array of validation chains for various fields (`username`, `email`, `password`, `age`) for a `/register` endpoint. Each chain specifies rules like minimum length, email format, password complexity (using regex), and integer checks. Importantly, it also includes sanitization methods like `trim()`, `escape()`, and `normalizeEmail()` to clean the input. If validation fails, `validationResult(req)` collects errors, and the API returns a 400 Bad Request response with detailed error messages. This prevents malformed or malicious data from reaching your application's core logic or database, enhancing security and data integrity.