JAVASCRIPT

Server-Side Input Validation with `express-validator`

Implement robust server-side input validation and sanitization using `express-validator` to protect against injection attacks and ensure data integrity in your Node.js application.

const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded

/**
 * Middleware for user registration validation and sanitization.
 */
const validateRegistration = [
  // Validate and sanitize email
  body('email')
    .isEmail().withMessage('Please enter a valid email address.')
    .normalizeEmail(), // Sanitizes email (e.g., converts to lowercase)

  // Validate password strength
  body('password')
    .isLength({ min: 8 }).withMessage('Password must be at least 8 characters long.')
    .matches(/[A-Z]/).withMessage('Password must contain at least one uppercase letter.')
    .matches(/[a-z]/).withMessage('Password must contain at least one lowercase letter.')
    .matches(/[0-9]/).withMessage('Password must contain at least one number.')
    .matches(/[^A-Za-z0-9]/).withMessage('Password must contain at least one special character.')
    .trim(), // Sanitizes password (removes leading/trailing whitespace)

  // Validate username
  body('username')
    .trim()
    .isLength({ min: 3, max: 20 }).withMessage('Username must be between 3 and 20 characters.')
    .matches(/^[a-zA-Z0-9_]+$/).withMessage('Username can only contain letters, numbers, and underscores.')
    .escape(), // Sanitizes username (escapes HTML entities, helps prevent XSS if data is re-rendered)

  // Validate age (example for numeric input)
  body('age')
    .optional()
    .isInt({ min: 18, max: 120 }).withMessage('Age must be a number between 18 and 120.')
    .toInt() // Sanitizes age (converts to integer)
];

// Route to handle user registration
app.post('/register', validateRegistration, (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 { email, password, username, age } = req.body;
  console.log('User registered with:', { email, username, age });
  // In a real application, you would save this user to a database

  res.status(200).json({ message: 'User registered successfully!' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Send POST requests to http://localhost:3000/register with JSON or form-urlencoded data.');
  console.log('Example: POST /register { "email": "[email protected]", "password": "Passw0rd!", "username": "testuser", "age": 25 }');
});
How it works: This snippet demonstrates server-side input validation and sanitization using the `express-validator` library for Node.js Express applications. It defines a middleware array (`validateRegistration`) that applies various checks and sanitizers to incoming request data (e.g., email, password, username, age). After validation, `validationResult` collects any errors. If errors exist, a 400 response is sent; otherwise, the sanitized data can be safely processed, protecting against common vulnerabilities like injection attacks and ensuring data integrity. The `escape()` sanitizer is used on the username to prevent storing potentially malicious HTML entities, guarding against XSS if the data were later rendered unescaped.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs