How to Use express-validator for Input Validation in Express
Use
express-validator by importing its validation middlewares like check or body, then add them as middleware in your Express routes to validate inputs. After validation, use validationResult(req) to check for errors and handle them accordingly.Syntax
The main parts of express-validator are validation middlewares and the error result checker.
check(field)orbody(field): Define validation rules for a specific input field.- Validation chain methods like
.isEmail(),.notEmpty(),.isLength(): Specify the validation rules. validationResult(req): Extracts validation errors from the request.
javascript
import express from 'express'; import { check, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); app.post('/route', [ check('fieldName').isEmail().withMessage('Must be a valid email'), check('password').isLength({ min: 6 }).withMessage('Password too short') ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // proceed if no errors });
Example
This example shows a simple Express server validating an email and password on a POST request to /register. It returns errors if validation fails or success message if inputs are valid.
javascript
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); app.post('/register', [ body('email').isEmail().withMessage('Enter a valid email'), body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters') ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.json({ message: 'Registration successful' }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Output
Server running on port 3000
POST /register with invalid email or short password returns 400 with errors array.
POST /register with valid inputs returns { message: 'Registration successful' }
Common Pitfalls
Common mistakes include:
- Not calling
validationResult(req)to check errors, so invalid input passes silently. - Forgetting to use
express.json()middleware, causingreq.bodyto be undefined. - Not returning or ending the response after sending errors, leading to multiple responses.
javascript
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); // Wrong: Missing validationResult check app.post('/wrong', [ body('email').isEmail() ], (req, res) => { // No error check here res.send('No validation done'); }); // Right: Proper error handling app.post('/right', [ body('email').isEmail() ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.send('Valid input'); });
Quick Reference
| Function | Purpose | Example |
|---|---|---|
| check(field) | Create validation chain for any request field | check('username').notEmpty() |
| body(field) | Create validation chain for body fields | body('email').isEmail() |
| validationResult(req) | Get validation errors from request | const errors = validationResult(req) |
| withMessage(msg) | Add custom error message | body('password').isLength({ min: 6 }).withMessage('Too short') |
| isEmail() | Validate field is an email | body('email').isEmail() |
| isLength({ min }) | Validate minimum length | body('password').isLength({ min: 6 }) |
Key Takeaways
Use validation middlewares like check() or body() to define rules for inputs.
Always call validationResult(req) to check for errors after validation.
Include express.json() middleware to parse JSON request bodies.
Return or end the response immediately after sending validation errors.
Use withMessage() to provide clear error messages for users.