Skip to content

Express Validator

Express Validator is a library for validating and sanitizing user input in Express.js applications. It helps ensure that incoming data (from forms, APIs, etc.) meets the expected format and is safe to use.

Why Use Express Validator?

  • Input Validation: Ensures that required fields are provided and in the correct format (e.g., email is in the right format, passwords are long enough).
  • Input Sanitization: Removes unwanted characters to prevent security risks like SQL injection or XSS attacks.
  • Error Handling: Provides detailed error messages when validation fails.

How to Use Express Validator?

  • Install the library
Terminal window
npm install express-validator
  • Import it in your code:
Terminal window
const { body, validationResult } = require('express-validator');
  • Use it as middleware to validate input.

Example: A Simple Signup Form

const express = require("express");
const { body, validationResult } = require("express-validator");
const app = express();
app.use(express.json()); // Allows JSON in the request body
// Route for user signup
app.post(
"/signup",
[
body("email").isEmail().withMessage("Enter a valid email"), // Check if email is valid
body("password")
.isLength({ min: 6 })
.withMessage("Password must be at least 6 characters long"), // Check password length
],
(req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() }); // Send errors as a response
}
res.send("Signup successful!");
}
);
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});

How It Works:

1. Define Validation Rules:

  • Use body('field') to specify which field to validate.
  • Add validation methods like .isEmail() or .isLength(). Check for Errors: Use validationResult(req) to collect errors. Return errors if any exist, or proceed with the request.

1. Check for Errors:

  • Use validationResult(req) to collect errors.
  • Return errors if any exist, or proceed with the request.

Example Request and Response:

Request Body:

{
"email": "invalidemail",
"password": "123"
}

Response (if validation fails):

{
"errors": [
{ "msg": "Enter a valid email" },
{ "msg": "Password must be at least 6 characters long" }
]
}

Response (if validation passes):

Signup successful!

Common Validation Methods:

  • .isEmail(): Checks if the input is a valid email.
  • .notEmpty(): Ensures the field is not empty.
  • .isLength({ min: x }): Validates the input length.
  • .matches(regex): Validates input against a regular expression.
  • .isNumeric(): Checks if the value is numeric.