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.
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:
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.
Contact Us