Dino Geek, try to help you

How to validate incoming requests with joi or express-validator?


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.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use