Input Validation in Node.js

From the Express.js cheat sheet · Request Validation · verified Jul 2026

Input Validation

Validate and sanitize user input to ensure data integrity

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

// Validation middleware
app.post('/users',
  body('email').isEmail().normalizeEmail(),
  body('name').isLength({ min: 2 }).trim().escape(),
  body('age').isInt({ min: 0, max: 120 }),
  body('password').isLength({ min: 8 }).matches(/\d/),
  (req, res) => {
    // Check validation results
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    
    // Process valid data
    const { email, name, age, password } = req.body;
    // Create user...
  }
);
💡 Always validate user input
✅ Sanitize data to prevent XSS
⚠️ Return clear validation error messages
🔒 Never trust client-side validation alone
Back to the full Express.js cheat sheet