How to Validate Data using joi Module in Node.js ? - GeeksforGeeks

15 Feb, 2021
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.Introduction:  
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.
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 joiAfter installing multer you can check your joi version in command prompt using the command.  npm ls joiAfter 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.  node index.jsRequiring module: You need to include joi module in your file by using these lines.  const Joi = require('joi');
You can visit the link Install joi module. You can install this package by using this command.  npm install joi
npm install joi
After installing multer you can check your joi version in command prompt using the command.  npm ls joi
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.  node index.js
node index.js
Requiring module: You need to include joi module in your file by using these lines.  const Joi = require('joi');
const Joi = require('joi');
Filename: index.js  
javascript
const Joi = require('joi')  //User-defined function to validate the userfunction validateUser(user){    const JoiSchema = Joi.object({              username: Joi.string()                  .min(5)                  .max(30)                  .required(),                            email: Joi.string()               .email()               .min(5)               .max(50)               .optional(),                          date_of_birth: Joi.date()                       .optional(),                                 account_status: Joi.string()                        .valid('activated')                        .valid('unactivated')                        .optional(),    }).options({ abortEarly: false });      return JoiSchema.validate(user)}  const user = {    username: 'Pritish',    email: 'pritish@gmail.com',    date_of_birth: '2020-8-11',    account_status: 'activated'}  response = validateUser(user)  if(response.error){      console.log(response.error.details)}else{    console.log("Validated Data")}
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 joiRun index.js file using below command:  node index.jsNow, 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:  
The project structure will look like this:
Make sure you have installed the joi module by using the following command:  npm install joi
npm install joi
Run index.js file using below command:  node index.js
node index.js
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:  
javascript
var user = {    username: 'GH',    email: 'demo@',    date_of_birth: '2020-20-48',    account_status: 'abcd'};
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. 
pritishnagpal
NodeJS-Questions
Node.js
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript