How to Validate Data using joi Module in Node.js ?
Last Updated :
13 Jun, 2024
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 to joi
- 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.
Approach
To validate data in Node.js using the Joi module, define a schema with specific validation rules. Use schema.validate(data) method to check if the data conforms to these rules, handling any validation errors that arise.
Steps to Implement Data Validation using joi
Step 1: Installation of joi module
You can install this package by using this command.
npm install joi
Step 2: After installing multer you can check your joi version in command prompt using the command.
npm ls joi
The Updated Dependencies in Package.json file
"dependencies": {
"joi": "^17.13.1",
}
Step 3: 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
Step 4: Import module
You need to include joi module in your file by using these lines.
const Joi = require('joi');
Example: Below example demonstrates data validation using joi module in a node app.
Node
// Filename - index.js
const Joi = require('joi')
//User-defined function to validate the user
function 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: '[email protected]',
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: Run index.js file using below command:
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.
Similar Reads
How to Validate Data using validator Module in Node.js ?
The Validator module is popular for validation. Validation is necessary to check whether the data is correct or not, so this module is easy to use and validates data quickly and easily. Feature of validator module: It is easy to get started and easy to use.It is a widely used and popular module for
2 min read
How to Validate Data using express-validator Module in Node.js ?
Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module:Â Â You can
3 min read
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
How to Create and Validate JSON Schema in MongoDB?
JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated. In this article, we will cover how to create and validate JSON Schema in MongoDB using
5 min read
How to Post Data in MongoDB Using NodeJS?
In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
5 min read
How to load and validate form data using jQuery EasyUI ?
EasyUI is a HTML5 framework for using user interface components based on jQuery, React, Angular and, Vue technologies. It helps in building features for interactive web and mobile applications saving a lot of time for developers. It helps in building features for interactive web and mobile applicati
4 min read
How to Upload File using formidable module in Node.js ?
A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads.ApproachTo upload file using the formidable module in node we will first install formidable. Then create an HTTP server to ac
2 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to check if a string is valid MongoDB ObjectId in Node.js ?
Checking if a string is valid mongoDB ObjectID is important while working with databases. It ensures accurate reference the the objects in databases. We can validate the ObjectId with the help of isValid function in MongoDB.Prerequisites:NodeJS and NPM installedMongoose and MongoDBTable of ContentMo
3 min read