Express.js Input Validation
Input validation checks incoming data before the app uses it. A browser, a mobile app, or a script can send anything to an Express route. Some users make typing mistakes. Some users send harmful data on purpose. Validation acts as a checkpoint that lets good data pass and stops bad data at the door.
Picture an airport security gate. Every passenger passes through the same scanner before reaching the plane. Validation plays that role for every request that reaches a route.
Why Validation Matters
- It blocks empty or broken values before they reach the database.
- It protects the app from injection attacks.
- It returns clear messages that help users fix their mistakes.
- It keeps stored data clean and consistent.
The browser can check a form too, but a user can bypass browser checks with simple tools. The server must always run its own checks.
Validation Flow Diagram
Request with body data
|
v
+---------------------+
| Validation rules |
+---------------------+
| |
Valid Invalid
| |
v v
Controller 400 error with
runs list of problems
Install express-validator
The express-validator package offers ready-made rules for common checks. Install it with npm.
npm install express-validatorValidate a Sign-Up Route
The example below checks a name, an email, and a password. The rules sit in an array before the route handler.
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
const signupRules = [
body('name').trim().notEmpty().withMessage('Name is required'),
body('email').isEmail().withMessage('Enter a valid email'),
body('password')
.isLength({ min: 8 })
.withMessage('Password needs at least 8 characters')
];
app.post('/signup', signupRules, (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.status(201).json({ message: 'Account created' });
});
app.listen(3000);How the Code Works
The body Function
The body function targets one field inside the request body. Chain rules after it to build a full check for that field.
The validationResult Function
The validationResult function collects every failed rule. An empty list means the data passed. A filled list holds one entry per problem.
The Error Response
A failed request returns status 400 with a JSON list. Each entry names the field and carries the message from withMessage.
Common Rules
| Rule | Purpose |
|---|---|
| notEmpty() | Rejects blank values |
| isEmail() | Checks the email format |
| isInt({ min: 1 }) | Accepts whole numbers above zero |
| isLength({ min, max }) | Limits text size |
| isIn(['a','b']) | Allows only listed values |
| trim() | Removes extra spaces |
| escape() | Replaces risky HTML characters |
Validate Params and Query Strings
Validation covers more than the body. Use param for route parameters and query for query strings.
const { param, query } = require('express-validator');
app.get('/users/:id', param('id').isInt(), (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.json({ id: req.params.id });
});
app.get('/search', query('page').optional().isInt({ min: 1 }), (req, res) => {
res.json({ page: req.query.page || 1 });
});Reuse a Validation Middleware
Repeating the error check in every route wastes effort. Move it into a small middleware and attach it after the rules.
function checkErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
}
app.post('/signup', signupRules, checkErrors, (req, res) => {
res.status(201).json({ message: 'Account created' });
});Best Practices
- Validate every field that comes from outside the app.
- Write short, friendly error messages.
- Sanitize text with trim and escape before saving it.
- Keep validation rules in their own file for each resource.
- Reject unknown fields when the data shape is strict.
Good validation turns a fragile API into a dependable one. Every route that accepts input deserves a rule set.
Real-World Scenario
A booking form accepts a guest name, a phone number, and a date. A visitor types letters in the phone field and leaves the date empty. The validation layer catches both problems and returns two clear messages. The database never sees the broken data, and the visitor fixes the form in seconds.
