When building an Express.js API, receiving data from the client is easy.
For example:
app.post("/users", (req, res) => {
console.log(req.body);
});
But here's the important question:
Can we trust the data coming from the client?
The answer is no.
A client could send:
{
"name": "",
"email": "hello",
"age": "abc"
}
Or something completely unexpected:
{
"name": 123,
"email": true,
"age": []
}
If your API directly stores this data in the database, you can quickly end up with invalid or inconsistent data.
This is where data validation comes in.
In this article, we'll learn:
- What data validation is
- Why API validation is important
- Where validation should happen
- Manual validation in Express.js
- Problems with manual validation
- What is a DTO?
- Why DTOs are useful
- DTO vs validation
- How to create a DTO
- What is
express-validator? - Installing and configuring
express-validator - Validating request body
- Validating route parameters
- Validating query parameters
- Sanitizing input
- Creating reusable validation middleware
- Handling validation errors
- Combining DTO + express-validator
- A production-friendly folder structure
- Common mistakes
Let's start.
What Is Data Validation?
Data validation means checking whether incoming data follows the rules expected by your application.
For example, suppose we're creating a user API.
We might have these rules:
name
→ required
→ must be a string
→ minimum 2 characters
email
→ required
→ must be a valid email
password
→ required
→ minimum 8 characters
age
→ must be a number
→ minimum 18
So if the client sends:
{
"name": "John",
"email": "john@example.com",
"password": "password123",
"age": 25
}
the request is valid.
But:
{
"name": "",
"email": "hello",
"password": "123",
"age": 10
}
should be rejected.
Why Is Data Validation Important?
Never assume that the frontend will always send correct data.
You might already have validation in React:
if (!email) {
setError("Email is required");
}
That's useful for user experience, but it is not enough.
A user can call your API directly using:
- Postman
- cURL
- Insomnia
- Browser developer tools
- Another application
- A custom script
They can completely bypass your frontend.
Therefore:
The backend must always validate incoming data independently.
Frontend validation improves the user experience.
Backend validation protects the application.
Example: What Can Go Wrong Without Validation?
Consider:
app.post("/users", async (req, res) => {
const user = await User.create(req.body);
res.json(user);
});
It looks simple.
But what if the request body is:
{
"name": 123,
"email": "invalid",
"password": "",
"role": "admin"
}
You could accidentally store invalid data.
Even worse, the client may try to send fields that should never be controlled by the client:
{
"name": "John",
"email": "john@example.com",
"role": "admin",
"isVerified": true
}
This is one reason why simply passing req.body directly into your database operations is not a good pattern.
Where Should Validation Happen?
A common Express.js request flow is:
Client
↓
Request
↓
Middleware
↓
Validation
↓
DTO / Data Transformation
↓
Controller
↓
Service
↓
Database
↓
Response
Validation should happen before business logic and database operations.
For example:
POST /users
↓
Validate request
↓
Invalid?
┌───┴───┐
Yes No
↓ ↓
400 DTO
↓
Controller
↓
Service
↓
Database
Manual Data Validation
Before using a validation library, let's understand how validation works manually.
Suppose we have:
app.post("/users", (req, res) => {
const { name, email, age } = req.body;
if (!name) {
return res.status(400).json({
message: "Name is required"
});
}
if (!email) {
return res.status(400).json({
message: "Email is required"
});
}
if (typeof age !== "number") {
return res.status(400).json({
message: "Age must be a number"
});
}
res.json({
message: "User is valid"
});
});
This works.
But imagine we have 20 fields.
The code becomes:
if...
if...
if...
if...
if...
if...
And when you have multiple endpoints, validation logic starts getting duplicated.
That's where a validation library becomes useful.
What Is a DTO?
DTO stands for:
Data Transfer Object
A DTO defines the shape of data that should be transferred between different parts of an application.
In simple terms:
A DTO is a controlled representation of the data your application expects to receive or send.
For example, suppose the client sends:
{
"name": "John",
"email": "john@example.com",
"password": "password123",
"role": "admin"
}
But when creating a user, your API only needs:
name
email
password
A DTO can define exactly what should be accepted:
const createUserDTO = {
name: req.body.name,
email: req.body.email,
password: req.body.password
};
Now role is not automatically passed into the user creation logic.
DTO Is Not the Same as Validation
This distinction is important.
Validation asks:
Is this data valid?
DTO asks:
What data should we transfer to the next layer?
For example:
{
"name": "John",
"email": "john@example.com",
"age": 25,
"role": "admin"
}
Validation might check:
name → valid
email → valid
age → valid
A DTO might select:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
The role field is excluded.
So:
Validation
↓
Checks correctness
DTO
↓
Controls data shape
They solve related but different problems.
Creating a Simple DTO
Let's create:
dto/
└── user.dto.js
const createUserDTO = (body) => {
return {
name: body.name,
email: body.email,
password: body.password
};
};
module.exports = {
createUserDTO
};
Then in your controller:
const {
createUserDTO
} = require("../dto/user.dto");
const createUser = async (req, res) => {
const userData = createUserDTO(req.body);
console.log(userData);
// Save userData to database
res.status(201).json({
message: "User created successfully"
});
};
Now the controller doesn't blindly use:
req.body
Instead, it uses the DTO.
Why Not Directly Use req.body?
Consider:
User.create(req.body);
This means you're trusting the entire request body.
That can be dangerous because the client controls the request.
A safer pattern is:
const userData = createUserDTO(req.body);
User.create(userData);
Now you explicitly control what gets passed to your database layer.
DTO as a Data Boundary
You can think of a DTO as a boundary between external data and your application.
External Request
↓
req.body
↓
Validation
↓
DTO
↓
Application Logic
↓
Database
This helps prevent unexpected fields from leaking into your business logic.
DTO Example with Transformation
DTOs can also transform data.
Suppose the client sends:
{
"name": " John ",
"email": " JOHN@EXAMPLE.COM "
}
The DTO could transform it:
const createUserDTO = (body) => {
return {
name: body.name.trim(),
email: body.email.trim().toLowerCase()
};
};
Now the application receives:
{
"name": "John",
"email": "john@example.com"
}
This is another useful purpose of DTOs.
What Is express-validator?
express-validator is a collection of Express.js middleware functions that makes request validation easier.
Instead of manually writing:
if (!email) ...
if (!password) ...
if (!name) ...
you can define validation rules.
For example:
body("email")
.isEmail()
.withMessage("Please provide a valid email");
You can combine multiple rules:
body("password")
.notEmpty()
.withMessage("Password is required")
.isLength({ min: 8 })
.withMessage("Password must contain at least 8 characters");
Installing express-validator
Install the package:
npm install express-validator
Then import what you need:
const {
body,
validationResult
} = require("express-validator");
Your First express-validator Example
Let's create a user API.
const express = require("express");
const {
body,
validationResult
} = require("express-validator");
const app = express();
app.use(express.json());
app.post(
"/users",
[
body("name")
.notEmpty()
.withMessage("Name is required"),
body("email")
.isEmail()
.withMessage("Invalid email"),
body("password")
.isLength({ min: 8 })
.withMessage(
"Password must be at least 8 characters"
)
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
res.status(201).json({
message: "User created successfully"
});
}
);
Let's understand what is happening.
Step 1: Validate Name
body("name")
.notEmpty()
.withMessage("Name is required")
This checks whether name is present and not empty.
If the client sends:
{
"name": ""
}
validation fails.
Step 2: Validate Email
body("email")
.isEmail()
.withMessage("Invalid email")
This checks whether the value looks like a valid email address.
For example:
john@example.com
is valid.
But:
hello
is not.
Step 3: Validate Password
body("password")
.isLength({ min: 8 })
.withMessage(
"Password must be at least 8 characters"
);
This requires at least 8 characters.
Step 4: Get Validation Errors
After the validation middleware runs:
const errors = validationResult(req);
This retrieves validation errors stored on the request.
Then:
if (!errors.isEmpty()) {
checks whether errors exist.
Step 5: Return the Errors
return res.status(400).json({
errors: errors.array()
});
The API can return something like:
{
"errors": [
{
"type": "field",
"msg": "Invalid email",
"path": "email",
"location": "body"
}
]
}
The exact shape can vary with the version and configuration of express-validator, but the important idea is that you get structured validation errors.
Validating Required Fields
A common rule is:
body("name")
.notEmpty()
.withMessage("Name is required");
You can also use:
body("name")
.exists()
.withMessage("Name is required");
There is an important difference.
exists()
Checks whether the field exists.
notEmpty()
Checks that the field isn't empty.
For most user input fields, you'll often want a combination of presence and meaningful content depending on your requirements.
Validating String Length
For example:
body("username")
.isLength({ min: 3, max: 20 })
.withMessage(
"Username must be between 3 and 20 characters"
);
Validating Numbers
You can validate numbers using:
body("age")
.isInt({ min: 18 })
.withMessage(
"Age must be an integer greater than or equal to 18"
);
For example:
{
"age": 25
}
is valid.
Validating Boolean Values
body("isActive")
.isBoolean()
.withMessage(
"isActive must be a boolean"
);
Expected input:
{
"isActive": true
}
Validating Specific Values
Suppose a user can have only:
user
admin
manager
You can use:
body("role")
.isIn(["user", "admin", "manager"])
.withMessage("Invalid role");
Now:
{
"role": "admin"
}
is valid.
But:
{
"role": "superadmin"
}
will fail this validation.
Validating Password Confirmation
Suppose your request is:
{
"password": "password123",
"confirmPassword": "password123"
}
You can validate the confirmation field:
body("confirmPassword")
.custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error(
"Passwords do not match"
);
}
return true;
});
This is useful for custom business-related validation rules.
Validating Route Parameters
So far we've validated:
req.body
But Express applications also receive parameters.
For example:
GET /users/123
Here:
req.params.id
contains:
123
express-validator provides:
param()
for validating route parameters.
Example:
const {
param,
validationResult
} = require("express-validator");
app.get(
"/users/:id",
[
param("id")
.isInt()
.withMessage("User ID must be an integer")
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
res.json({
id: req.params.id
});
}
);
Validating Query Parameters
Suppose the client requests:
GET /users?page=1&limit=10
You can access:
req.query.page
req.query.limit
Use:
query()
to validate them.
const {
query,
validationResult
} = require("express-validator");
app.get(
"/users",
[
query("page")
.isInt({ min: 1 })
.withMessage(
"Page must be a positive integer"
),
query("limit")
.isInt({ min: 1, max: 100 })
.withMessage(
"Limit must be between 1 and 100"
)
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
res.json({
page: req.query.page,
limit: req.query.limit
});
}
);
body(), param(), and query()
It's useful to remember these three.
Request body
body("email")
Used for:
POST
PUT
PATCH
request data.
Route parameter
param("id")
Used for:
/users/:id
Query parameter
query("page")
Used for:
/users?page=1
Sanitizing Input
Validation checks whether input is acceptable.
Sanitization modifies input into a cleaner form.
For example:
body("email")
.trim()
.normalizeEmail()
.isEmail()
.withMessage("Invalid email");
Suppose the client sends:
" JOHN@EXAMPLE.COM "
The value can be normalized before it reaches your application logic.
Another example:
body("name")
.trim()
.escape();
The exact sanitization you need depends on the data and how you use it.
Validation and Sanitization Are Different
This distinction is worth remembering.
Validation
Checks:
Is the data acceptable?
Example:
body("email").isEmail()
Sanitization
Transforms:
Can we clean or normalize the data?
Example:
body("email").trim().normalizeEmail()
They are often used together.
Creating Reusable Validation Middleware
If every controller contains this:
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
you are going to repeat the same code.
Instead, create a reusable middleware.
Create:
middleware/
└── validate.js
const {
validationResult
} = require("express-validator");
const validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
next();
};
module.exports = validate;
Now your route becomes much cleaner.
Using the Validation Middleware
const {
body
} = require("express-validator");
const validate = require("../middleware/validate");
router.post(
"/users",
[
body("name")
.notEmpty()
.withMessage("Name is required"),
body("email")
.isEmail()
.withMessage("Invalid email"),
body("password")
.isLength({ min: 8 })
.withMessage(
"Password must be at least 8 characters"
)
],
validate,
createUser
);
Now the flow is:
Request
↓
Validation rules
↓
validate middleware
↓
Errors?
┌───┴───┐
Yes No
↓ ↓
400 Controller
Response ↓
Service
This is much cleaner.
Creating a Separate Validation File
As the application grows, don't put every validation rule inside your route file.
Instead:
src/
├── controllers/
│ └── user.controller.js
│
├── routes/
│ └── user.routes.js
│
├── validations/
│ └── user.validation.js
│
├── middleware/
│ └── validate.js
│
└── server.js
Create:
validations/user.validation.js
const {
body
} = require("express-validator");
const createUserValidation = [
body("name")
.trim()
.notEmpty()
.withMessage("Name is required")
.isLength({ min: 2 })
.withMessage(
"Name must contain at least 2 characters"
),
body("email")
.trim()
.isEmail()
.withMessage("Invalid email"),
body("password")
.isLength({ min: 8 })
.withMessage(
"Password must contain at least 8 characters"
)
];
module.exports = {
createUserValidation
};
Using Validation Rules in Routes
Now:
const express = require("express");
const {
createUserValidation
} = require("../validations/user.validation");
const validate = require("../middleware/validate");
const router = express.Router();
router.post(
"/users",
createUserValidation,
validate,
createUser
);
module.exports = router;
This makes the route much easier to read.
Adding a DTO
Now let's combine validation and DTO.
Create:
dto/user.dto.js
const createUserDTO = (body) => {
return {
name: body.name,
email: body.email,
password: body.password
};
};
module.exports = {
createUserDTO
};
Then:
const {
createUserDTO
} = require("../dto/user.dto");
const createUser = async (req, res, next) => {
try {
const userData = createUserDTO(req.body);
// Business logic
// const user = await userService.create(userData);
res.status(201).json({
message: "User created successfully"
});
} catch (error) {
next(error);
}
};
Now we have a clear separation.
Validation
↓
Is input valid?
↓
DTO
↓
Which data should enter the application?
↓
Controller
↓
Business logic
A Complete Example
Let's put everything together.
Project Structure
src/
│
├── controllers/
│ └── user.controller.js
│
├── dto/
│ └── user.dto.js
│
├── middleware/
│ ├── validate.js
│ └── errorHandler.js
│
├── routes/
│ └── user.routes.js
│
├── validations/
│ └── user.validation.js
│
└── server.js
server.js
const express = require("express");
const userRoutes = require("./routes/user.routes");
const errorHandler = require("./middleware/errorHandler");
const app = express();
app.use(express.json());
app.use("/api", userRoutes);
app.use(errorHandler);
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
user.validation.js
const {
body
} = require("express-validator");
const createUserValidation = [
body("name")
.trim()
.notEmpty()
.withMessage("Name is required")
.isLength({ min: 2 })
.withMessage(
"Name must contain at least 2 characters"
),
body("email")
.trim()
.isEmail()
.withMessage("Invalid email"),
body("password")
.isLength({ min: 8 })
.withMessage(
"Password must contain at least 8 characters"
)
];
module.exports = {
createUserValidation
};
validate.js
const {
validationResult
} = require("express-validator");
const validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
message: "Validation failed",
errors: errors.array()
});
}
next();
};
module.exports = validate;
user.dto.js
const createUserDTO = (body) => {
return {
name: body.name,
email: body.email,
password: body.password
};
};
module.exports = {
createUserDTO
};
user.controller.js
const {
createUserDTO
} = require("../dto/user.dto");
const createUser = async (req, res, next) => {
try {
const userData = createUserDTO(req.body);
console.log(userData);
// Save userData to database
res.status(201).json({
message: "User created successfully"
});
} catch (error) {
next(error);
}
};
module.exports = {
createUser
};
user.routes.js
const express = require("express");
const {
createUserValidation
} = require("../validations/user.validation");
const validate = require("../middleware/validate");
const {
createUser
} = require("../controllers/user.controller");
const router = express.Router();
router.post(
"/users",
createUserValidation,
validate,
createUser
);
module.exports = router;
errorHandler.js
const errorHandler = (
err,
req,
res,
next
) => {
console.error(err);
res.status(500).json({
message: "Internal server error"
});
};
module.exports = errorHandler;
Now the complete flow looks like:
POST /api/users
↓
express.json()
↓
createUserValidation
↓
validate
↓
createUser
↓
createUserDTO
↓
Business Logic
↓
Database
↓
Response
This is a clean pattern for a growing Express.js application.
Validation Error Response
Suppose the client sends:
{
"name": "",
"email": "hello",
"password": "123"
}
The API can return:
{
"message": "Validation failed",
"errors": [
{
"msg": "Name is required",
"path": "name"
},
{
"msg": "Invalid email",
"path": "email"
},
{
"msg": "Password must contain at least 8 characters",
"path": "password"
}
]
}
The frontend can use these errors to display appropriate messages to the user.
What About Database Validation?
This is another important point.
API validation and database validation are not necessarily the same thing.
For example, your API might validate:
email must be valid
password must be at least 8 characters
But your database might enforce:
email must be unique
Both layers are useful.
Think of it like:
Client
↓
API Validation
↓
Business Rules
↓
Database Constraints
Don't depend on only one layer.
Validation vs DTO vs Database Model
These three concepts are often confused.
Validation
Checks incoming data.
Is email valid?
Is password long enough?
Is age a number?
DTO
Controls the data shape passed between application layers.
Which fields should we accept?
Which fields should we transform?
Database Model
Defines how data is stored.
For example:
User
├── name
├── email
├── passwordHash
└── createdAt
They have different responsibilities.
A Simple Mental Model
Remember this:
Request
↓
Validation
"Is this data valid?"
↓
DTO
"What data do we actually want?"
↓
Controller
"What operation is being requested?"
↓
Service
"What business rules should happen?"
↓
Database
"How should the data be stored?"
This separation becomes increasingly useful as your application grows.
Common Mistakes to Avoid
1. Trusting Frontend Validation
Don't assume this is enough:
if (!email) {
showError();
}
Users can bypass the frontend.
Always validate on the backend.
2. Passing req.body Directly to the Database
Avoid:
User.create(req.body);
Prefer explicitly selecting the fields you need:
const userData = createUserDTO(req.body);
User.create(userData);
3. Mixing Validation With Business Logic
Avoid:
const createUser = async (req, res) => {
if (!req.body.email) {
// validation
}
if (req.body.password.length < 8) {
// validation
}
// database logic
// business logic
// response
};
For larger applications, move validation into dedicated middleware.
4. Returning Different Validation Formats
If one API returns:
{
"error": "Invalid email"
}
and another returns:
{
"errors": [
{
"field": "email",
"message": "Invalid email"
}
]
}
your frontend becomes harder to maintain.
Try to establish a consistent validation error format across your API.
5. Validating Only the Request Body
Don't forget:
req.params
req.query
req.headers
For example:
/users/:id
has a route parameter.
And:
/users?page=1
has query parameters.
All external input should be treated carefully.
When Should You Use DTOs?
DTOs become particularly useful when:
- Your application has multiple layers.
- You don't want controllers to pass raw request data around.
- You want to explicitly control accepted fields.
- You need to transform incoming data.
- You have different request and response shapes.
- Your application is growing.
For a tiny Express application, a separate DTO layer may feel like extra code.
That's okay.
Don't introduce architecture just for the sake of architecture.
But as the application grows, DTOs can make data flow much easier to understand and control.
When Should You Use express-validator?
express-validator is useful when:
- You are building Express REST APIs.
- You need reusable validation rules.
- You validate body, params, and query parameters.
- You want structured validation errors.
- You want common sanitization operations.
- You want validation logic separated from controllers.
For simple APIs, manual validation may be enough.
For larger APIs, a dedicated validation library usually saves time and reduces repetitive code.
Final Thoughts
Data validation is not just an optional feature in an Express.js application.
It is an important part of building reliable APIs.
The frontend can validate data for a better user experience, but the backend must perform its own validation because the backend cannot assume that requests are coming from your frontend.
express-validator makes this process easier by providing reusable validation rules:
body("email")
.isEmail()
.withMessage("Invalid email");
DTOs solve a different problem.
They help control the data that enters your application:
const createUserDTO = (body) => {
return {
name: body.name,
email: body.email,
password: body.password
};
};
A clean Express.js request flow can look like:
Client
↓
Express Middleware
↓
Validation
↓
DTO
↓
Controller
↓
Service
↓
Database
↓
Response
The key idea is simple:
Validation checks whether the data is acceptable, while a DTO controls what data your application actually works with.
Once you understand this distinction, building larger and more maintainable Express.js APIs becomes much easier.