How to use Joi for data Validation in NodeJS

AJIM
2 min readFeb 18, 2023

--

When developing backend applications or APIs, there is always a need to do some data validation in order to be sure that our users are sending us the correct data. Writing all this validation logic manually can be time-consuming and tedious, and there are already NPM packages to help us with this. Today we will be looking at a package called Joi which is used for data validation.

Setup

First of all, we will install Joi in our project directory using this command:

npm i joi

Then let’s go ahead and import it into our JavaScript file.

cosnt Joi = require('joi');

Usage

Here, we have to create a Joi schema which is an object that contains all the property names of our data and also the data type/constraints as the value of those properties. Let’s check out the example below:

cosnt Joi = require('joi');

const schema = Joi.object({
username: Joi.string().required().min(5).max(30),
age: Joi.number().min(10).max(50).required(),
email: Joi.string().email().required(),
password: Joi.string().pattern(/^[a-zA-Z0-9]{3,30}$/).required(),
repeat_password: Joi.ref("password"),
isAdmin: Joi.boolean().default(false)
})

In the code above, we create a variable called schema which is of a Joi object type, then we have the various properties such as [username, age, email...] and their corresponding values that specify the data types and constraints. Some data types that exist in Joi are [string, number, object, boolean etc. We also have constraints for setting the default value default(), making a field required required(), checking if an email is a valid email email(), using regular expressions to check the password strength password() etc.

cosnt Joi = require('joi');

const schema = Joi.object({
username: Joi.string().required().min(5).max(30),
age: Joi.number().min(10).max(50).required(),
email: Joi.string().email().required(),
password: Joi.string().pattern(/^[a-zA-Z0-9]{3,30}$/).required(),
repeat_password: Joi.ref("password"),
isAdmin: Joi.boolean().default(false)
})
const {error, value} = schema.validate({
username: 'Ajims',
age: '20',
email: 'a@b.co',
password: 'h4Rct5A',
repeat_password: '4Rct5A'
})
if(error) console.error(error.details[0].message)
console.log(value)

Here, we are validating our data against the schema which returns an error if the data doesn’t match our schema specification and a value(a value is always returned even if there is an error). If there is a problem, the error message is logged to the console else the value (which is basically the data we passed in) will be logged.

--

--

AJIM
AJIM

No responses yet