JAVASCRIPT
Robust Server-Side Input Validation and Sanitization
Implement comprehensive server-side input validation and sanitization using `express-validator` in Node.js to protect against various injection attacks and ensure data integrity.
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
const port = 3000;
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.post('/register', [
// Validate and sanitize username
body('username').trim().isLength({ min: 3 }).withMessage('Username must be at least 3 characters long'),
body('username').matches(/^[a-zA-Z0-9_]+$/).withMessage('Username can only contain letters, numbers, and underscores'),
// Validate and sanitize email
body('email').normalizeEmail().isEmail().withMessage('Invalid email address'),
// Validate password strength (example: min 8 chars, 1 uppercase, 1 lowercase, 1 number)
body('password').isLength({ min: 8 }).withMessage('Password must be at least 8 characters long'),
body('password').matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/).withMessage('Password must contain at least one uppercase letter, one lowercase letter, and one number'),
// Validate age as a positive integer, sanitize to integer
body('age').isInt({ gt: 0 }).withMessage('Age must be a positive integer').toInt(),
// Custom validation for terms agreement
body('terms').custom(value => {
if (value !== true && value !== 'true') {
throw new Error('You must agree to the terms and conditions');
}
return true;
})
], (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, age } = req.body;
console.log('Validated and Sanitized Data:', { username, email, age });
res.status(200).json({ message: 'Registration successful', data: { username, email, age } });
});
app.get('/', (req, res) => {
res.send('Send POST request to /register with username, email, password, age, terms');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates robust server-side input validation and sanitization using the `express-validator` library. It is crucial for web applications to validate all incoming user data to prevent various security vulnerabilities such as injection attacks (e.g., SQL injection, NoSQL injection, command injection) and to ensure data integrity. The example shows how to chain validation rules (`isLength`, `isEmail`, `matches`, `isInt`) and sanitization methods (`trim`, `normalizeEmail`, `toInt`) for different input fields like username, email, password, and age. It also includes custom validation for a terms agreement checkbox. After validation, `validationResult()` collects any errors, allowing the server to respond with appropriate feedback or proceed with processing the clean, sanitized data if all checks pass.