1. Create Middleware Function :
- Define a custom middleware function that takes req, res , and next as parameters. Use validation libraries like joi , express-validator, or custom validation logic.
2. Validate Request Data :
- Extract the relevant data from the request body , query parameters , or headers. Apply validation rules using the chosen library or custom logic.
3. Error Handling :
- Implement a global error handler middleware to catch validation errors and other errors. Send a formatted error response to the client , including a suitable HTTP status code and error details.
//javascript
const express = require('express');
const Joi = require('joi');
const app = express();
const userSchema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
age: Joi.number().min(18).max(100),
});
function validateUser(req , res , next ){
const {error} = userSchema.validate(req.body);
if(error) {
return next(error);
}
next();
}
app.post('/users' , validateUser , (req , res) => {
// Create a new user
});
app.use((err , req , res , next ) => {
res.status(400).json({error: err.message });
});