To implement API request validation in Express using middleware, you can use an external library like `express-validator` or `joi`. Here's a simple example using `express-validator`:
1. Install express-validator: First, you need to install the package using npm.
npm install express-validator
2. Set up middleware: Create a validation middleware for your route.
const { body, validationResult } = require('express-validator');
const validateRequest = [
body('username').isString().isLength({ min: 5 }).withMessage('Username should be valid.'),
body('email').isEmail().withMessage('Email address should be valid.'),
body('password').isLength({ min: 6 }).withMessage('Use strong Password.'),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(300).json({ errors: errors.array() });
}
next();
}
];
3. Use the middleware in a route:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/register', validateRequest, (req, res) => {
// Handle the request knowing that validation has passed
res.send('User registered successfully.');
});
app.listen(5000, () => {
console.log('Server running on port 5000');
});
In the above example `validateRequest` middleware used to check for a valid username, email and password in the request body. For fail validations, it responds with a 300 status code and an array of error messages.
If everything is valid, it calls the `next()` function to proceed to the actual route handler.
Related Question : Implement role-based access control in a full-stack application