- First, install the required package using the npm command in your terminal:
npm install celebrate
- Next, create a new file to define your Joi validation schema, for example, userValidation.js. Define your schema using the Joi library.
- Import the celebrate and Joi libraries at the beginning of your main file.
- Use the celebrate middleware to validate the incoming requests in your Node.js route handlers. For example:
const { celebrate, Joi } = require('celebrate');
- Apply the celebrate middleware to the desired route, providing the validation schema as an argument. For example:
router.post('/example', celebrate({
body: {
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(0).max(200)
}
}), (req, res) => {
// Handle the validated request
});