NPM joi

In any JavaScript application, ensuring that data conforms to a specific structure or set of rules is crucial for maintaining data integrity and application reliability. Schema validation is the process of verifying that the data adheres to predefined rules or constraints. One popular tool for performing schema validation in JavaScript applications is Joi.

What is Joi

Joi is a powerful schema validation library for JavaScript applications. It provides a simple and expressive API for defining schemas and validating data against those schemas. Originally developed as part of the hapi.js framework, Joi has since been extracted into a standalone package and can be used in any JavaScript environment, including Node.js and browser-based applications.

Steps to Setup Project and Install npm Joi

Step 1: First to install the NodeJS form the official website (Download NodeJS).

Step 2: Create a NodeJS app using the below command:

npm init -y

Step 3: Navigate to the root directory using the below command.

cd foldername

Step 3: Install the joi dependency using the below command.

npm joi

The updated dependencies in your package.json file is look like:

"dependencies"{
"joi": "^17.13.1",
}

Key Features of Joi

1. Declarative Schema Definition

Joi allows developers to define data validation rules using a declarative syntax. Schemas can be expressed as plain JavaScript objects, making them easy to understand and maintain.

const Joi = require('joi');

const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(18).max(100),
});

2. Built-in Validators

Joi provides a rich set of built-in validators for common data types and constraints, such as strings, numbers, dates, arrays, and more. Validators can be chained together to create complex validation rules.

const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(18).max(100),
});

3. Custom Validators

In addition to built-in validators, Joi allows developers to define custom validation rules using custom validator functions. This enables validation logic tailored to specific application requirements.

const customValidator = (value, helpers) => {
if (!value.startsWith('https://')) {
return helpers.error('any.invalid');
}
return value;
};

const schema = Joi.object({
url: Joi.string().custom(customValidator, 'custom validation'),
});

Validation Options

Joi allows developers to customize validation behavior through various options, such as allowing unknown keys in objects, stripping unknown keys, converting values to their respective types, and more.

const schema = Joi.object({
username: Joi.string().alphanum().required(),
}).options({ allowUnknown: true });

Example: Below is an example to validate the data using the joi package.

JavaScript
const express = require('express');
const Joi = require('joi');

const app = express();
const port = 5000;

// Middleware to parse JSON requests
app.use(express.json());

// Define a Joi schema for validating user input
const schema = Joi.object({
    username: Joi.string().alphanum().min(3).max(30).required(),
    email: Joi.string().email().required(),
    age: Joi.number().integer().min(18).max(100),
});

// POST endpoint for validating user input
app.post('/validate', (req, res) => {
    // Validate the request body against the schema
    const { error, value } = schema.validate(req.body);

    // If validation fails, return an error response
    if (error) {
        return res.status(400).json({
            error: error.details[0].message
        });
    }

    // If validation succeeds, return a success response
    return res.json({ message: 'Data is valid', data: value });
});

// Start the server
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

Output:

Conclusion

Joi is a powerful and versatile schema validation library for JavaScript applications. Its declarative syntax, rich set of validators, error handling capabilities, and customization options make it a popular choice for ensuring data integrity and application reliability. By incorporating Joi into your projects, you can streamline the validation process and build more robust and maintainable applications.



Contact Us