Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.
- It’s easy to get started and easy to use.
- It is widely used and popular module for data validation.
- It supports schema based validation.
Installation of joi module:
- You can visit the link Install joi module. You can install this package by using this command.
npm install joi
- After installing multer you can check your joi version in command prompt using the command.
npm ls joi
- After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
- Requiring module: You need to include joi module in your file by using these lines.
const Joi = require('joi');
Note: In the above program abortEarly is set to false which makes sure that if there are multiple errors then all are displayed in the terminal. If it is set to true then the execution of the program will stop as soon as the first error is encountered and only that error will be displayed in the terminal.
Steps to run the program:
- The project structure will look like this:
- Make sure you have installed the joi module by using the following command:
npm install joi
- Run index.js file using below command:
- Now, if no error occurs i.e. user data is validate, then following output will be produced:
- Now, if we validate the user against the invalid data as shown below, then the following output will be produced:
If abortEarly is set to true the following output will be produced :
So this is how you can validate data using joi module. There are other modules in the market for validation like express-validator, etc.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.