Validating Requests in Express: Because Users Will Send Anything

Hi, I'm Vishal Gupta, a passionate and self-driven Full-Stack Developer with a strong command of the MERN stack (MongoDB, Express.js, React.js, Node.js). I love turning complex problems into clean, scalable solutions through elegant code and user-friendly interfaces. With hands-on experience building real-world applications like MedEase, TripGenius, and now this Expense Tracker, I strive to build software that’s not only functional but also impactful. Whether it's creating secure authentication systems, responsive UI components, or integrating AI-powered features, I aim to deliver value with every line of code. 🔧 Key Skills: Frontend: React.js, Vite, Tailwind CSS, ShadCN, Context API Backend: Node.js, Express.js, MongoDB, JWT, REST APIs Dev Tools: Git & GitHub, Postman, Firebase, Vercel Soft Skills: Problem-solving, communication, and a strong desire to learn & grow I believe in continuous learning and building meaningful products that solve real-life problems. Currently, I’m open to opportunities where I can collaborate, innovate, and contribute to exciting web development projects.
When you build APIs, one of the most important tasks is making sure the data coming from the client is valid, clean, and safe.
This is where express-validator becomes extremely useful.
Instead of writing long, repetitive validation code, express-validator gives you a clean and simple way to check request data using middleware.
Let’s walk through what it is, why it matters, and how to use it properly.
What Is express-validator?
express-validator is a middleware library that helps validate and sanitize incoming request data in Express.
It allows you to:
check if fields are present
validate email formats
check password lengths
ensure numbers are actually numbers
sanitize values
prevent unsafe or incorrect data
It works by adding validation rules inside your routes, using small middlewares.
Why Do We Use express-validator?
Without validation:
clients can send broken or empty data
your database may store incorrect values
users can accidentally (or intentionally) break your API
your server must manually check everything
With express-validator:
validation is consistent
errors are easy to return
logic stays in one place
routes remain clean
middleware handles most of the work
It makes your API more secure and predictable.
Installing express-validator
Run this:
npm install express-validator
That’s it.
Basic Example of express-validator
Here is how you validate input when creating a user:
const { body, validationResult } = require("express-validator");
app.post(
"/users",
[
body("name").notEmpty().withMessage("Name is required"),
body("email").isEmail().withMessage("Email is invalid"),
body("password").isLength({ min: 6 }).withMessage("Password must be at least 6 characters long"),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.status(201).send("User created");
}
);
Here’s how it works:
Each
body()call is a middleware that checks a fieldIf validation fails, errors are stored
validationResult()collects themYou send back a clear error response
How express-validator Middleware Works
Validation happens before your route handler runs.
Order:
Middlewares check values
If valid → moves to next middleware
If invalid → you return an error
Route handler runs only when input is correct
This keeps your logic clean and safe.
Validating Different Parts of the Request
express-validator can validate:
Body fields
body("username").notEmpty()
URL parameters
param("id").isInt()
Query parameters
query("limit").isInt({ min: 1 })
Headers
header("x-api-key").notEmpty()
Example: Validating Route Parameters
const { param } = require("express-validator");
app.delete(
"/products/:id",
[param("id").isMongoId().withMessage("Invalid product ID")],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send("Product deleted");
}
);
This ensures the ID in the URL is valid before running delete logic.
Example: Validating Query Parameters
app.get(
"/search",
[
query("keyword").notEmpty().withMessage("Keyword is required"),
query("page").optional().isInt({ min: 1 }).withMessage("Page must be a number"),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send("Search results");
}
);
Now your search endpoint has safe inputs.
Sanitizing Input with express-validator
Besides validating, express-validator can sanitize data:
Trim spaces
body("name").trim()
Normalize email
body("email").normalizeEmail()
Convert to number
body("age").toInt()
Sanitizing helps keep your stored data clean and consistent.
Creating Custom Validators
You can define your own rules:
body("password").custom((value) => {
if (value.includes("123")) {
throw new Error("Password is too weak");
}
return true;
});
Custom validators give you complete control.
Keeping Validation Clean Using a Separate Middleware File
To avoid clutter in your routes, you can move validation rules to another file.
validators/userValidators.js
const { body } = require("express-validator");
exports.createUserValidator = [
body("name").notEmpty().withMessage("Name is required"),
body("email").isEmail().withMessage("Valid email is required"),
body("password").isLength({ min: 6 }).withMessage("Password must be 6+ characters"),
];
In your route:
app.post("/users", createUserValidator, (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
res.send("User created");
});
Much cleaner.
Summary
express-validator helps you validate user input easily and safely using middleware. It keeps your routes clean, improves security, and avoids storing broken data.
With express-validator, you can:
check body, params, query, and headers
apply multiple rules per field
send structured error messages
sanitize and clean input
write custom validators
keep validation logic organized
It is one of the most practical tools you’ll use when building robust Express APIs.
Thank you for reading till the end. I am grateful.
If you see any errors or face any difficulty in the blog,
Do let me know through comments or write to me on this
abhimanyug987@gmail.com


