How to Validate Data using hapi/joi Module in Node.js ?

Hapi/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:

  1. It’s easy to get started and easy to use.
  2. It is widely used and popular module for data validation.
  3. It supports schema based validation.

Installation of @hapi/joi module:

  1. You can visit the link Install @hapi/joi module. You can install this package by using this command.
    npm install @hapi/joi
  2. After installing multer you can check your @hapi/joi version in command prompt using the command.
    npm version @hapi/joi
  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
  4. Requiring module: You need to include @hapi/joi module in your file by using these lines.
    var Joi = require('@hapi/joi');

Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

const Joi = require('@hapi/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)
}
  
var user = {
    username: 'Gourav',
    email: 'gourav@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")
}

chevron_right


Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have installed @hapi/joi module by using the following command:
    npm install @hapi/joi
  3. 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:
    Output of above command

  4. Now, if we validate the user against the invalid data as shown below, then the following output will be produced:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    var user = {
        username: 'GH',
        email: 'demo@',
        date_of_birth: '2020-20-48',
        account_status: 'abcd'
    };

    chevron_right

    
    

    Output of incorrect user

So this is how you can validate data using @hapi/joi module. There are other modules in the market for validation like express-validator, etc.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.