Joi is a strong and adaptable JavaScript validation package used for schema modeling and data validation. It offers a practical method to validate and apply rules to data objects, making it simpler to maintain data consistency and integrity in applications.
Joi is compatible with front-end and back-end JavaScript platforms like Node.js and browser-based frameworks. It provides an easy-to-use declarative API for creating schemas and implementing data validation rules.
We can design schemas using Joi that specify the restrictions and structure of our data objects. Data of all kinds, including characters, integers, booleans, arrays, objects, and more, can be included in schemas. Joi offers a large selection of pre-built validation rules and permits the definition of unique validations.
We can add the following dependency under the dependencies
section in our package.json
file:
"joi" :"17.9.2"
Alternatively, we can install it globally using the following command:
npm install joi@17.9.2
Joi
libraryWe can import the Joi
library using the following command:
const Joi = require('joi');
Following is the schema on which we will validate our data:
// Define a schemaconst schema = Joi.object({username: Joi.string().alphanum().min(3).max(30).required(),password: Joi.string().pattern(new RegExp('^(?=.*[a-zA-Z0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{3,30}$')).required(),email: Joi.string().email({ tlds: { allow: false } }),});
The functions that we have used to create our schema mean the following:
Joi.string()
: Specifies that the field should be a string.
.alphanum()
: Requires that the string contains only alphanumeric characters (both letters and numbers). Special characters or spaces are not allowed.
.min(3)
: Sets a minimum length requirement of 3
characters for the field.
.max(30)
: Sets a maximum length limit of 30
characters for the field.
.required()
: Makes the field mandatory, meaning it must be provided in the data being validated. If the field is missing or null, the validation will fail.
.pattern(new RegExp('^(?=.*[a-zA-Z0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{3,30}$'))
: Defines a pattern-based validation for the password field using a regular expression (RegExp).
.email({ tlds: { allow: false } })
: Specifies that the string should be in the format of an email address. The tlds
option is used to configure the validation of top-level domains (TLDs). In this case, { allow: false }
disallows the TLDs, meaning the email addresses without the TLDs (e.g., “example@domain”) are considered valid.
username: Joi.string().alphanum().min(3).max(30).required()
: Specifies that the username field should be a string containing only alphanumeric characters, with a minimum length of 3
characters and a maximum length of 30
characters. It is required.
password: Joi.string().pattern(new RegExp('^(?=.*[a-zA-Z0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{3,30}$')).required()
: Specifies that the password field should be a string, matching the specified pattern using a regular expression. The pattern enforces at least one alphanumeric character and one special character from the set !@#$%^&*
, with a length between 3
and 30
characters. It is also required.
email Joi.string().email({ tlds: { allow: false } })
: Specifies that the email field should be a string in the format of an email address. The option, { tlds: { allow: false } }
, ensures that top-level domains (TLDs) are not allowed.
Following are the inputs that we will try to validate:
// It will passconst data1 = {username: 'educative123',password: 'Educative@secret$756',email: 'educative@educative.io',};// It will fail due to an invalid passwordconst data2 = {username: 'educative123',password: 'Educativesecret756',email: 'educative@educative.io',};// It will fail due to an invalid emailconst data3 = {username: 'educative123',password: 'Educative@secret$756',email: 'educative.educative.io',};
The data1
input is validated successfully because all the fields are valid.
The data2
input fails because of an invalid password.
The data3
input fails because of an invalid email.
The code below validates the inputs on the given schema:
Line 1: We import the joi
library.
Lines 4–8: We define our schema for the username
, password
, and email
fields.
Lines 13–30: We define the inputs that we want to validate.
Lines 33–53: We perform the validation of our inputs and print the results. If the validation is passed, the “Validation succeeded” message is printed on the screen. If the validation fails, the “Validation failed” message along with the reason is printed on the screen.
Free Resources