How to use the Joi library with JavaScript
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.
Installation
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
Importing the Joi library
We can import the Joi library using the following command:
const Joi = require('joi');
Defining the schema
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 of3characters for the field. -
.max(30): Sets a maximum length limit of30characters 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. Thetldsoption 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.
What do our validations mean?
-
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 of3characters and a maximum length of30characters. 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 between3and30characters. 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.
Defining our inputs to be validated
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
data1input is validated successfully because all the fields are valid. -
The
data2input fails because of an invalid password. -
The
data3input fails because of an invalid email.
Validating our data
The code below validates the inputs on the given schema:
Explanation
Line 1: We import the
joilibrary.Lines 4–8: We define our schema for the
username,password, andemailfields.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