Both Joi and express-validator are popular libraries for validating inputs in a Node.js application. Here is how you can use them.
1. Validation with Joi:
You have to start by installing Joi in your project:
```
npm install @hapi/joi
```
Then you can use it in your express application like this:
```
const Joi = require(‘@hapi/joi’);
const schema = Joi.object({
username: Joi.string().min(6).required(),
email: Joi.string().min(6).required().email(),
password: Joi.string().min(6).required()
});
app.post(‘/register’, async (req, res) => {
const validation = schema.validate(req.body);
if (validation.error) {
res.status(400).send(validation.error.details0.message);
return;
}
// Continue with your logic
});
```
1. Validation with express-validator:
First, you have to install it:
```
npm install express-validator
```
Then, you can use it like this:
```
const { check, validationResult } = require(‘express-validator’);
app.post(‘/user’, [ // username must be an email check(‘username’).isEmail(), // password must be at least 5 chars long check(‘password’).isLength({ min: 5 }) ], (req, res) => { // Finds the validation errors in this request and wraps them in an object with handy functions const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); }
// Continue with your logic }); ```In both cases, if the validation fails, the server will respond with a 400 status code and a clear error message. If everything is okay, you can continue with your other logic, like saving the user’s data into your database.