Data validation with the Joi package

Capítulo 120

Estimated reading time: 5 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

A crucial aspect when creating APIs in NodeJS is data validation. Data validation is a process that ensures that data entered into an application is accurate, complete and meets all established business rules. To facilitate this process, we can use the Joi package, a powerful data validation library for JavaScript.

Joi lets you create complex data validation schemas with a minimum of code and effort. It provides a variety of data types and validation rules, making it an extremely flexible and powerful tool for any NodeJS project.

When working with APIs, data validation is essential to ensure data integrity and prevent data entry errors. For example, when creating an API for a user management system, you might need to ensure that the username is a string, that the email address is valid, and that the password meets certain complexity criteria. Joi can help with all that and more.

To start using Joi, we first need to install it in our NodeJS project. This can be done using the npm package manager with the following command: npm install @hapi/joi.

Once installed, we can import Joi into our file and start creating validation schemas. A schema is a description of the validation rules we want to apply to our data. For example, we can create a schema to validate user input like this:

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app

const Joi = require('@hapi/joi');

const schema = Joi.object({
  name: Joi.string().min(3).max(30).required(),
  email: Joi.string().email().required(),
  password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),
});

In this example, the schema defines that the name must be a string with a minimum of 3 characters and a maximum of 30, the email address must be a string that passes email validation, and the password must be a string that matches a specific regular expression.

To validate the input data with this schema, we can use Joi's validate() method. This method returns an object that contains details about any validation errors that may have occurred. For example:

const userInput = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  password: 'password123',
};

const validationResult = schema.validate(userInput);

if (validationResult.error) {
  console.log(validationResult.error.details);
} else {
  console.log('User input is valid');
}

If user input fails validation, the validate() method returns an object that contains details about the error, including the error message and the path to the invalid value. We may use this information to inform the user of the error and how to correct it.

Joi also supports validation of more complex data types such as arrays and objects. For example, we can validate an array of strings as follows:

const arraySchema = Joi.array().items(Joi.string());

const arrayInput = ['apple', 'banana', 'cherry'];

const arrayValidationResult = arraySchema.validate(arrayInput);

if (arrayValidationResult.error) {
  console.log(arrayValidationResult.error.details);
} else {
  console.log('Array input is valid');
}

In the same way, we can validate an object that contains other objects or arrays. For example, we can validate an object representing a user and their addresses as follows:

const addressSchema = Joi.object({
  street: Joi.string().required(),
  city: Joi.string().required(),
  state: Joi.string().required(),
  zip: Joi.string().required(),
});

const userSchema = Joi.object({
  name: Joi.string().required(),
  email: Joi.string().email().required(),
  addresses: Joi.array().items(addressSchema),
});

const userInput = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  addresses: [
    {
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      zip: '12345',
    },
    {
      street: '456 Elm St',
      city: 'Anytown',
      state: 'CA',
      zip: '12345',
    },
  ],
};

const validationResult = userSchema.validate(userInput);

if (validationResult.error) {
  console.log(validationResult.error.details);
} else {
  console.log('User input is valid');
}

In short, Joi is a powerful and flexible tool for validating data in NodeJS projects. It can handle a variety of data types and validation rules, making it an excellent choice for any project that requires robust data validation.

Now answer the exercise about the content:

What is the main role of Joi library in NodeJS projects?

You are right! Congratulations, now go to the next page

You missed! Try again.

The main role of the Joi library in NodeJS projects is to validate data entered into the application. Joi offers a variety of data types and validation rules, to create complex validation schemas with minimal code and effort, ensuring data integrity and preventing input errors.

Next chapter

File upload with Multer in NodeJS

Arrow Right Icon
Free Ebook cover How to create APIs in NodeJS from basic to advanced
81%

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.