Joi Data Validation Library
Introduction
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.
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 JOI Data Validation
1) Install The joi Modul
npm install joi2) Create Separate File to Use Joi Data Validation
index.js3) Import Joi Library
const Joi = require('joi');Example for Validate Data using joi
// Filename - index.js
const Joi = require('joi') << Import joi Library >>
//User-defined function to validate the user
function validateUser(user)
{
const JoiSchema = Joi.object({ << Create joi Validation Object >>
username: Joi.string() << Check username is ‘string >>
.min(5) << Check minimum length of string is ‘5’ >>
.max(30) << Check maximum length of string is ‘30’ >>
.required(), << username is ‘can’t be null’ >>
email: Joi.string() << Check email is ‘string’ >>
.email() << Check email is in ‘Valid email’ Format >>
.min(5) << Check minimum length of email is ‘5’ >>
.max(50) << Check maximum length of email is ‘50’ >>
.optional(), << Email is can be ‘optional’ >>
date_of_birth: Joi.date() << Check date_of_birth is in Date Format >>
.optional(), << Email is can be ‘optional’ >>
account_status: Joi.string() << Check account_status is ‘string’
.valid('activated') << Check it Value is equal Accepted value >>
.valid('unactivated') << Check it Value is equal Accepted value >>
.optional(), << account_status is can be ‘optional’ >>
}).options({ abortEarly: false });
return JoiSchema.validate(user) << Return Validation Error >>
}
const user = { << The user Data Object Need to Validate >>
username: 'Pramod',
email: 'pramod@gmail.com',
date_of_birth: '1999-04-10',
account_status: 'activated'
}
response = validateUser(user)
if(response.error) << Check That Function Return Validation Error >>
{
console.log(response.error.details) << Return Validation Error >>
}
else
{
console.log("Validated Data") << If There is no Error, Return ‘Validated data’ >>
}Joi Validation Options ( Methods )
1) String Type Check
- .alphanum(): String must contain only alphanumeric characters.
- .min(length): Minimum length of the string.
- .max(length): Maximum length of the string.
- .pattern(regex): String must match the given regular expression.
- .email(): String must be a valid email address.
- .required(): The value must be present.
Example :
Joi.string().min(3).max(30).required();2) Number Type Check
- .integer(): Number must be an integer.
- .min(value): Minimum value.
- .max(value): Maximum value.
- .greater(value): Number must be greater than the given value.
- .less(value): Number must be less than the given value.
- .positive(): Number must be positive.
- .negative(): Number must be negative
Get Pramod Jayansiri’s stories in your inbox
Join Medium for free to get updates from this writer.
Example :
Joi.number().integer().min(0).max(100);3) Boolean Type Check
Example :
Joi.boolean();4) Date Type Check
- .greater(‘now’): Date must be greater than now.
- .less(‘now’): Date must be less than now.
- .iso(): Date must be in ISO 8601 format.
Example :
Joi.date().greater('now');5) Array Type Check
- .items(schema): Specifies the schema for the items in the array.
- .min(length): Minimum number of items in the array.
- .max(length): Maximum number of items in the array.
- .unique(): Ensures all items in the array are unique
Example :
Joi.array().items(Joi.string()).min(1).max(5);6) Object Type Check
- .keys(schema): Specifies the schema for the object keys.
- .required(): The object must be present.
Example :
Joi.object({
username: Joi.string().required(),
password: Joi.string().required(),
});7) Any Type Check — A general schema type that can be used when the value can be of any type.
- .allow(value): Allows the specified values in addition to the regular type checks.
- .valid(value): The value must be one of the specified values.
- .default(value): Sets a default value.
Example :
Joi.any().allow(null);8) Alternative Check — Defines a schema that can have multiple possible types.
- .try(schemas): Tries the given schemas in order until one matches
Example :
Joi.alternatives().try(Joi.string(), Joi.number());









