Object schema description language and validator for JavaScript objects.
Current version: 4.0.x
- [Example](#example) - [Usage](#usage) - [`validate(value, schema, [options], callback)`](#validatevalue-schema-options-callback) - [`compile(schema)`](#compileschema) - [`any()`](#any) - [`any.allow(value)`](#anyallowvalue) - [`any.valid(value)`](#anyvalidvalue) - [`any.invalid(value)`](#anyinvalidvalue) - [`any.required()`](#anyrequired) - [`any.optional()`](#anyoptional) - [`description(desc)`](#descriptiondesc) - [`any.notes(notes)`](#anynotesnotes) - [`any.tags(tags)`](#anytagstags) - [`any.options(options)`](#anyoptionsoptions) - [`any.strict()`](#anystrict) - [`any.default(value)`](#anydefault) - [`array()`](#array) - [`array.includes(type)`](#arrayincludestype) - [`array.excludes(type)`](#arrayexcludestype) - [`array.min(limit)`](#arrayminlimit) - [`array.max(limit)`](#arraymaxlimit) - [`array.length(limit)`](#arraylengthlimit) - [`binary()`](#binary) - [`binary.min(limit)`](#binaryminlimit) - [`binary.max(limit)`](#binarymaxlimit) - [`binary.length(limit)`](#binarylengthlimit) - [`boolean()`](#boolean) - [`date()`](#date) - [`date.min(date)`](#datemindate) - [`date.max(date)`](#datemaxdate) - [`func()`](#func) - [`number()`](#number) - [`number.min(limit)`](#numberminlimit) - [`number.max(limit)`](#numbermaxlimit) - [`number.integer()`](#numberinteger) - [`object([schema])`](#objectschema) - [`object.keys([schema])`](#objectkeysschema) - [`object.min(limit)`](#objectminlimit) - [`object.max(limit)`](#objectmaxlimit) - [`object.length(limit)`](#objectlengthlimit) - [`object.with(key, peers)`](#objectwithkey-peers) - [`object.without(key, peers)`](#objectwithoutkey-peers) - [`object.xor(peers)`](#objectxorpeers) - [`object.or(peers)`](#objectorpeers) - [`object.rename(from, to, [options])`](#objectrenamefrom-to-options) - [`string()`](#string) - [`string.insensitive()`](#stringinsensitive) - [`string.min(limit)`](#stringminlimit) - [`string.max(limit)`](#stringmaxlimit) - [`string.length(limit)`](#stringlengthlimit) - [`string.regex(pattern)`](#stringregexpattern) - [`string.alphanum()`](#stringalphanum) - [`string.token()`](#stringtoken) - [`string.email()`](#stringemail) - [`string.guid()`](#stringguid) - [`string.isoDate()`](#stringisodate) - [`alternatives(types)`](#alternativestypes) - [Migration notes](#migration-notes)var Joi = require('joi');
var schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email()
}).with('username', 'birthyear').without('password', 'access_token');
Joi.validate({ username: 'abc', birthyear: 1994 }, schema, function (err) { }); // err === null -> validThe 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
birthyear
password- an optional string
- must satisfy the custom regex
- cannot appear together with
access_token
access_token- an optional, unconstrained string or number
birthyear- an integer between 1900 and 2013
email- a valid email address string
Usage is a two steps process. First, a schema is constructed using the provided types and constraints:
var schema = {
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.
Then the value is validated against the schema:
Joi.validate({ a: 'a string' }, schema, function (err) { });If the value is valid, null is returned, otherwise an Error object.
The schema can be a plain JavaScript object where every key is assigned a joi type, or it can be a joi type directly:
var 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:
var schema = Joi.object({
a: Joi.string()
});When validating a schema:
- Keys are optional by default.
- Strings are utf-8 encoded by default.
- Rules are defined in an additive fashion and evaluated in order after whitelist and blacklist checks.
Validates a value using the given schema and options where:
value- the value being validated.schema- the validation schema. Can be a joi type object or a plain object where every key is assigned a joi type object.options- an optional object with the following optional keys:abortEarly- whentrue, stops validation on the first error, otherwise returns all the errors found. Defaults totrue.convert- whentrue, attempts to cast values to the required types (e.g. a string to a number). Defaults totrue.allowUnknown- whentrue, allows object to contain unknown keys which are ignored. Defaults tofalse.skipFunctions- whentrue, ignores unknown keys with a function value. Defaults tofalse.stripUnknown- whentrue, unknown keys are deleted (only when value is an object). Defaults tofalse.language- overrides individual error messages. Defaults to no override ({}).
callback- the callback method using the signaturefunction(err, callback)where:err- if validation failed, the error reason, otherwisenull.value- the validated value with any type conversions and other modifiers applied (the input is left unchanged).valuecan be incomplete if validation failed andabortEarlyistrue.
var schema = {
a: Joi.number()
};
var value = {
a: '123'
};
Joi.validate(value, schema, function (err) { });
// err -> null
// value.a -> 123 (number, not string)Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object) where:
schema- the schema definition to compile.
var definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];
var schema = Joi.compile(definition);
// Same as:
var schema = Joi.alternatives([
Joi.string().valid('key'),
Joi.number().valid(5),
Joi.object({
a: Joi.boolean().valid(true),
b: Joi.alternatives([
Joi.string().regex(/^a/),
Joi.string().valid('boom')
])
})
]);Generates a schema object that matches any data type.
var any = Joi.any();
any.valid('a');
any.validate('a', function (err) { });Whitelists a value where:
value- the allowed value which can be of any type and will be matched against the validated value before applying any other rules.valuecan be an array of values, or multiple values can be passed as individual arguments.
var schema = {
a: Joi.any().allow('a'),
b: Joi.any().allow('b', 'B'),
c: Joi.any().allow(['c', 'C'])
};Adds the provided values into the allowed whitelist and marks them as the only valid values allowed where:
value- the allowed value which can be of any type and will be matched against the validated value before applying any other rules.valuecan be an array of values, or multiple values can be passed as individual arguments.
var schema = {
a: Joi.any().valid('a'),
b: Joi.any().valid('b', 'B'),
c: Joi.any().valid(['c', 'C'])
};Blacklists a value where:
value- the forbidden value which can be of any type and will be matched against the validated value before applying any other rules.valuecan be an array of values, or multiple values can be passed as individual arguments.
var schema = {
a: Joi.any().invalid('a'),
b: Joi.any().invalid('b', 'B'),
c: Joi.any().invalid(['c', 'C'])
};Marks a key as required which will not allow undefined as value. All keys are optional by default.
var schema = {
a: Joi.any().required()
};Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
var schema = {
a: Joi.any().optional()
};Annotates the key where:
desc- the description string.
var schema = Joi.any().description('this key will match anything you give it');Annotates the key where:
notes- the notes string or array of strings.
var schema = Joi.any().notes(['this is special', 'this is important']);Annotates the key where:
tags- the tag string or array of strings.
var schema = Joi.any().tags(['api', 'user']);Overrides the global validate() options for the current key and any sub-key where:
options- an object with the same optional keys asJoi.validate(value, schema, options, callback).
var schema = {
a: Joi.any().options({ convert: false })
};Sets the options.convert options to false which prevent type casting for the current key and any child keys.
var schema = {
a: Joi.any().strict()
};Sets a default value if the original value is undefined where:
value- the value.
var schema = {
username: Joi.string().default('new_user')
};
var input = {};
Joi.validate(input, schema, function (err) { });
// input === { username: "new_user" }Generates a schema object that matches an array data type.
Supports the same methods of the any() type.
var array = Joi.array();
array.includes(Joi.string().valid('a', 'b'));
array.validate(['a', 'b', 'a'], function (err) { });List the types allowed for the array values where:
type- a joi schema object to validate each array item against.typecan be an array of values, or multiple values can be passed as individual arguments.
var schema = {
a: Joi.array().includes(Joi.string(), Joi.number())
};List the types forbidden for the array values where:
type- a joi schema object to validate each array item against.typecan be an array of values, or multiple values can be passed as individual arguments.
var schema = {
a: Joi.array().excludes(Joi.object())
};Specifies the minimum number of items in the array where:
limit- the lowest number of array items allowed.
var schema = {
a: Joi.array().min(2)
};Specifies the maximum number of items in the array where:
limit- the highest number of array items allowed.
var schema = {
a: Joi.array().max(10)
};Specifies the exact number of items in the array where:
limit- the number of array items allowed.
var schema = {
a: Joi.array().length(5)
};Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
Supports the same methods of the any() type.
var boolean = Joi.boolean();
boolean.allow(null);
boolean.validate(true, function (err) { });Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
Supports the same methods of the any() type.
var schema = {
a: Joi.binary()
};Specifies the minimum length of the buffer where:
limit- the lowest size of the buffer.
var schema = {
a: Joi.binary().min(2)
};Specifies the maximum length of the buffer where:
limit- the highest size of the buffer.
var schema = {
a: Joi.binary().max(10)
};Specifies the exact length of the buffer:
limit- the size of buffer allowed.
var schema = {
a: Joi.binary().length(5)
};Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
Supports the same methods of the any() type.
var date = Joi.date();
date.min('12-20-2012');
date.validate('12-21-2012', function (err) { });Specifies the oldest date allowed where:
date- the oldest date allowed.
var schema = {
a: Joi.date().min('1-1-1974')
};Specifies the latest date allowed where:
date- the latest date allowed.
var schema = {
a: Joi.date().max('12-31-2020')
};Generates a schema object that matches a function type.
Supports the same methods of the any() type.
var func = Joi.func();
func.allow(null);
func.validate(function () {}, function (err) { });Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
Supports the same methods of the any() type.
var number = Joi.number();
number.min(1).max(10).integer();
number.validate(5, function (err) { });Specifies the minimum value where:
limit- the minimum value allowed.
var schema = {
a: Joi.number().min(2)
};Specifies the maximum value where:
limit- the maximum value allowed.
var schema = {
a: Joi.number().max(10)
};Requires the number to be an integer (no floating point).
var schema = {
a: Joi.number().integer()
};Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects) where:
schema- optional object where each key is assinged a joi type object. If the schema is{}no keys allowed. Defaults to 'undefined' which allows any child key.
Supports the same methods of the any() type.
var object = Joi.object({
a: Joi.number().min(1).max(10).integer()
});
object.validate({ a: 5 }, function (err) { });Sets the allowed object keys where:
schema- optional object where each key is assinged a joi type object. If the schema is{}no keys allowed. Defaults to 'undefined' which allows any child key. Overrides any keys previously set.
var object = Joi.object().keys({
a: Joi.number()
b: Joi.string()
});Specifies the minimum number of keys in the object where:
limit- the lowest number of keys allowed.
var schema = {
a: Joi.object().min(2)
};Specifies the maximum number of keys in the object where:
limit- the highest number of object keys allowed.
var schema = {
a: Joi.object().max(10)
};Specifies the exact number of keys in the object where:
limit- the number of object keys allowed.
var schema = {
a: Joi.object().length(5)
};Requires the presence of other keys whenever the specified key is present where:
key- the reference key.peers- the required peer key names that must appear together withkey.peerscan be a single string value or an array of string values.
var schema = Joi.object({
a: Joi.any(),
b: Joi.any()
}).with('a', 'b');Forbids the presence of other keys whenever the specified is present where:
key- the reference key.peers- the forbidden peer key names that must not appear together withkey.peerscan be a single string value or an array of string values.
var schema = Joi.object({
a: Joi.any(),
b: Joi.any()
}).without('a', ['b']);Defines an exclusive relationship between a set of keys where one of them is required but not at the same time where:
peers- the exclusive key names that must not appear together but where one of them is required.peerscan be a single string value, an array of string values, or each peer provided as an argument.
var schema = Joi.object({
a: Joi.any(),
b: Joi.any()
}).xor('a', 'b');Defines a relationship between keys where one of the peers is required (and more than one is allowed) where:
peers- the key names of which at least one must appear.peerscan be a single string value, an array of string values, or each peer provided as an argument.
var schema = Joi.object({
a: Joi.any(),
b: Joi.any()
}).or('a', 'b');Renames a key to another name (deletes the renamed key) where:
from- the original key name.to- the new key name.options- an optional object with the following optional keys:alias- iftrue, does not delete the old key name, keeping both the new and old keys in place. Defaults tofalse.multiple- iftrue, allows renaming multiple keys to the same destination where the last rename wins. Defaults tofalse.override- iftrue, allows renaming a key over an existing key. Defaults tofalse.
Keys are renamed before any other validation rules are applied.
var object = Joi.object({
a: Joi.number()
}).rename('b', 'a');
object.validate({ b: 5 }, function (err) { });Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
Supports the same methods of the any() type.
var string = Joi.string();
string.min(1).max(10);
string.validate('12345', function (err) { });Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
var schema = {
a: Joi.string().valid('a').insensitive()
};Specifies the minimum number string characters where:
limit- the minimum number of string characters required.
var schema = {
a: Joi.string().min(2)
};Specifies the maximum number of string characters where:
limit- the maximum number of string characters allowed.
var schema = {
a: Joi.string().max(10)
};Specifies the exact string length required where:
limit- the required string length.
var schema = {
a: Joi.string().length(5)
};Defines a regular expression rule where:
pattern- a regular expression object the string value must match against.
var schema = {
a: Joi.string().regex(/^[abc]+$/)
};Requires the string value to only contain a-z, A-Z, and 0-9.
var schema = {
a: Joi.string().alphanum()
};Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
var schema = {
a: Joi.string().token()
};Requires the string value to be a valid email address.
var schema = {
a: Joi.string().email()
};Requires the string value to be a valid GUID.
var schema = {
a: Joi.string().guid()
};Requires the string value to be in valid ISO 8601 date format.
var schema = {
a: Joi.string().isoDate()
};Generates a type that will match one of the provided alternative schemas where:
types- an array of alternaitve joi types. Also supports providing each type as a separate argument.
Supports the same methods of the any() type.
var alt = Joi.alternatives(Joi.number(), Joi.string());
alt.validate('a', function (err) { });Note that the alternatives() type does not behave the same way as passing multiple alternatives directly using an
array of types (e.g. { a: [Joi.number(), Joi.string()] }). When passing an array directly, the value must match one
of the provided types while when using the alternatives() type, the key is optional by default.