express-validator

7.3.2 · active · verified Wed Apr 22

express-validator is an active and widely used Express.js middleware library that provides a comprehensive suite of tools for validating and sanitizing request data. Currently at stable version 7.3.2, the library integrates directly with `validator.js`, offering a fluent API for defining validation chains for fields in the request body, query parameters, headers, or cookies. It typically releases patch and minor versions regularly, with major versions occurring less frequently (v7.0.0 was the first major update in almost four years). Key differentiators include its tight integration with Express's middleware system, robust error handling with `validationResult`, and extensive support for custom validators and sanitizers, making it a powerful solution for robust input validation in Node.js applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up an Express endpoint that uses `express-validator` to validate and sanitize user registration input. It checks for a non-empty username, a valid email format, and a minimum password length, returning appropriate error responses if validation fails.

import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
app.use(express.json()); // Middleware to parse JSON bodies

app.post('/register',
  body('username').notEmpty().withMessage('Username is required').trim().escape(),
  body('email').isEmail().withMessage('Must be a valid email address').normalizeEmail(),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    // If validation passes, process the registration
    const { username, email, password } = req.body;
    // In a real app, you would hash the password, save to DB, etc.
    console.log(`User registered: ${username}, ${email}`);
    res.status(201).json({ message: 'User registered successfully!' });
  }
);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

view raw JSON →