What is @hapi/joi?
@hapi/joi is a powerful schema description language and data validator for JavaScript. It allows you to define and validate data structures in a declarative way, making it easier to ensure that your data conforms to the expected format.
What are @hapi/joi's main functionalities?
Schema Validation
This feature allows you to define a schema for your data and validate it against that schema. The example demonstrates how to create a schema for a user object and validate an instance of that object.
const Joi = require('@hapi/joi');
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
birth_year: Joi.number().integer().min(1900).max(2013)
});
const value = {
username: 'abc',
password: 'password123',
birth_year: 1990
};
const result = schema.validate(value);
console.log(result);
Custom Error Messages
This feature allows you to customize error messages for different validation rules. The example shows how to provide custom error messages for the username and password fields.
const Joi = require('@hapi/joi');
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required().messages({
'string.base': 'Username should be a type of text',
'string.empty': 'Username cannot be an empty field',
'string.min': 'Username should have a minimum length of {#limit}',
'any.required': 'Username is a required field'
}),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).messages({
'string.pattern.base': 'Password must be alphanumeric and between 3 to 30 characters'
})
});
const value = {
username: '',
password: 'pw'
};
const result = schema.validate(value);
console.log(result.error.details);
Async Validation
This feature allows you to perform asynchronous validation, such as checking if an email is already taken in a database. The example demonstrates how to use an external async validation function within a Joi schema.
const Joi = require('@hapi/joi');
const schema = Joi.object({
email: Joi.string().email().external(async (value, helpers) => {
const isEmailTaken = await checkEmailInDatabase(value); // hypothetical async function
if (isEmailTaken) {
throw new Error('Email is already taken');
}
return value;
})
});
async function validateEmail(email) {
try {
await schema.validateAsync({ email });
console.log('Email is valid');
} catch (err) {
console.error(err.message);
}
}
validateEmail('test@example.com');
Other packages similar to @hapi/joi
yup
Yup is a JavaScript schema builder for value parsing and validation. It is similar to @hapi/joi in that it allows you to define schemas and validate data against them. However, Yup is often considered to be more lightweight and has a more modern API.
validator
Validator is a library of string validators and sanitizers. Unlike @hapi/joi, which is a comprehensive schema validation library, Validator focuses on providing a wide range of functions for validating and sanitizing strings.
ajv
Ajv is a JSON schema validator that is highly performant and supports JSON Schema standards. It is different from @hapi/joi in that it uses JSON Schema for validation, making it a good choice for applications that need to adhere to JSON Schema standards.
joi
The most powerful schema description language and data validator for JavaScript.
Introduction
joi lets you describe your data using a simple, intuitive, and readable language. Like the rest of the hapi ecosystem it fits in, joi allows you to describe your data for both input and output validation, as part of a hapi HTTP server or standalone.
API
See the detailed API Reference.
Example
const Joi = require('@hapi/joi');
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.pattern(/^[a-zA-Z0-9]{3,30}$/),
repeat_password: Joi.ref('password'),
access_token: [
Joi.string(),
Joi.number()
],
birth_year: Joi.number()
.integer()
.min(1900)
.max(2013),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
.with('username', 'birth_year')
.xor('password', 'access_token')
.with('password', 'repeat_password');
schema.validate({ username: 'abc', birth_year: 1994 });
schema.validate({});
try {
const value = await schema.validate({ username: 'abc', birth_year: 1994 });
}
catch (err) { }
The above schema defines the following constraints:
username
- a required string
- must contain only alphanumeric characters
- at least 3 characters long but no more than 30
- must be accompanied by
birth_year
password
- an optional string
- must satisfy the custom regex pattern
- cannot appear together with
access_token
- must be accompanied by
repeat_password
and equal to it
access_token
- an optional, unconstrained string or number
birth_year
- an integer between 1900 and 2013
email
- a valid email address string
- must have two domain parts e.g.
example.com
- TLD must be
.com
or .net
Usage
Usage is a two steps process:
First, a schema is constructed using the provided types and constraints:
const schema = Joi.object({
a: Joi.string()
});
Note that joi schema objects are immutable which means every additional rule added (e.g.
.min(5)
) will return a new schema object.
Second, the value is validated against the defined schema:
const { error, value } = schema.validate({ a: 'a string' });
schema.validate({ a: 'a string' }, function (error, value) { });
If the input is valid, then the error
will be null
. If the input is invalid, error
is assigned
a ValidationError
object
providing more information.
The schema can be a plain JavaScript object where every key is assigned a joi type, or it can be a joi type directly:
const schema = Joi.string().min(10);
If the schema is a joi type, the schema.validate(value, callback)
can be called directly on the type. When passing a non-type schema object,
the module converts it internally to an object() type equivalent to:
const schema = Joi.object().keys({
a: Joi.string()
});
When validating a schema:
-
Values (or keys in case of objects) are optional by default.
Joi.string().validate(undefined);
To disallow this behavior, you can either set the schema as required()
, or set presence
to "required"
when passing options
:
Joi.string().required().validate(undefined);
Joi.string().validate(undefined, { presence: "required" });
-
Strings are utf-8 encoded by default.
-
Rules are defined in an additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.