- Joi
version
validate(value, schema, [options], [callback])
compile(schema)
assert(value, schema, [message])
attempt(value, schema, [message])
ref(key, [options])
isRef(ref)
reach(schema, path)
defaults(fn)
extend(extension)
any
schemaType
any.validate(value, [options], [callback])
any.allow(value)
any.valid(value)
- aliases:only
,equal
any.invalid(value)
- aliases:disallow
,not
any.required()
- aliases:exist
any.optional()
any.forbidden()
any.strip()
any.description(desc)
any.notes(notes)
any.tags(tags)
any.meta(meta)
any.example(value)
any.unit(name)
any.options(options)
any.strict(isStrict)
any.default([value, [description]])
any.concat(schema)
any.when(condition, options)
any.label(name)
any.raw(isRaw)
any.empty(schema)
any.error(err)
array
- inherits fromAny
boolean
- inherits fromAny
binary
- inherits fromAny
date
- inherits fromAny
func
- inherits fromAny
number
- inherits fromAny
object
- inherits fromAny
object.keys([schema])
object.min(limit)
object.max(limit)
object.length(limit)
object.pattern(regex, schema)
object.and(peers)
object.nand(peers)
object.or(peers)
object.xor(peers)
object.with(key, peers)
object.without(key, peers)
object.rename(from, to, [options])
object.assert(ref, schema, [message])
object.unknown([allow])
object.type(constructor, [name])
object.schema()
object.requiredKeys(children)
object.optionalKeys(children)
object.forbiddenKeys(children)
string
- inherits fromAny
string.insensitive()
string.min(limit, [encoding])
string.max(limit, [encoding])
string.truncate([enabled])
string.creditCard()
string.length(limit, [encoding])
string.regex(pattern, [name | options])
string.replace(pattern, replacement)
string.alphanum()
string.token()
string.email([options])
string.ip([options])
string.uri([options])
string.guid()
- aliases:uuid
string.hex()
string.base64([options])
string.hostname()
string.normalize([form])
string.lowercase()
string.uppercase()
string.trim()
string.isoDate()
alternatives
- inherits fromAny
lazy(fn)
- inherits fromAny
- Errors
Property showing the current version of joi being used.
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 usingJoi.compile
(be careful of the cost of compiling repeatedly the same schemas).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
- remove unknown elements from objects and arrays. Defaults tofalse
.- when
true
, all unknown elements will be removed. - when an
object
:arrays
- set totrue
to remove unknown items from arrays.objects
- set totrue
to remove unknown keys from objects.
- when
language
- overrides individual error messages. Defaults to no override ({}
). Messages apply the following rules :- variables are put between curly braces like
{{var}}
, if prefixed by a!
like{{!var}}
, it will be html escaped if the optionescapeHtml
is also set totrue
- strings are always preceeded by the key name, unless a
{{key}}
is found elsewhere or if the string is prefixed by a!!
- when
'label'
is set, it overrides the key name in the error message - to better understand the structure of the language, it's advised to have a look at the existing messages you want to override here
- variables are put between curly braces like
presence
- sets the default presence requirements. Supported modes:'optional'
,'required'
, and'forbidden'
. Defaults to'optional'
.context
- provides an external data set to be used in references. Can only be set as an external option tovalidate()
and not usingany.options()
.noDefaults
- whentrue
, do not apply default values. Defaults tofalse
.escapeHtml
- whentrue
, error message templates will escape special characters to HTML entities, for security purposes. Defaults tofalse
.
callback
- the optional synchronous callback method using the signaturefunction(err, value)
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).value
can be incomplete if validation failed andabortEarly
istrue
. If callback is not provided, then returns an object with error and value properties.
When used without a callback, this function returns a Promise-like object that can be used as a promise, or as a simple object like in the below examples.
const schema = {
a: Joi.number()
};
const value = {
a: '123'
};
Joi.validate(value, schema, (err, value) => { });
// err -> null
// value.a -> 123 (number, not string)
// or
const result = Joi.validate(value, schema);
// result.error -> null
// result.value -> { "a" : 123 }
// or
const promise = Joi.validate(value, schema);
promise.then((value) => {
// value -> { "a" : 123 }
});
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.
const definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];
const schema = Joi.compile(definition);
// Same as:
const schema = Joi.alternatives().try([
Joi.string().valid('key'),
Joi.number().valid(5),
Joi.object().keys({
a: Joi.boolean().valid(true),
b: Joi.alternatives().try([
Joi.string().regex(/^a/),
Joi.string().valid('boom')
])
})
]);
Validates a value against a schema and throws if validation fails where:
value
- the value to validate.schema
- the validation schema. Can be a joi type object or a plain object where every key is assigned a joi type object usingJoi.compile
(be careful of the cost of compiling repeatedly the same schemas).message
- optional message string prefix added in front of the error message. may also be an Error object.
Joi.assert('x', Joi.number());
Validates a value against a schema, returns valid object, and throws if validation fails where:
value
- the value to validate.schema
- the validation schema. Can be a joi type object or a plain object where every key is assigned a joi type object usingJoi.compile
(be careful of the cost of compiling repeatedly the same schemas).message
- optional message string prefix added in front of the error message. may also be an Error object.
Joi.attempt('x', Joi.number()); // throws error
const result = Joi.attempt('4', Joi.number()); // result -> 4
Generates a reference to the value of the named key. References are resolved at validation time and in order of dependency so that if one key validation depends on another, the dependent key is validated second after the reference is validated. References support the following arguments:
key
- the reference target. References cannot point up the object tree, only to sibling keys, but they can point to their siblings' children (e.g. 'a.b.c') using the.
separator. If akey
starts with$
is signifies a context reference which is looked up in thecontext
option object.options
- optional settings:separator
- overrides the default.
hierarchy separator.contextPrefix
- overrides the default$
context prefix signifier.- Other options can also be passed based on what
Hoek.reach
supports.
Note that references can only be used where explicitly supported such as in valid()
or invalid()
rules. If upwards
(parents) references are needed, use object.assert()
.
const schema = Joi.object().keys({
a: Joi.ref('b.c'),
b: {
c: Joi.any()
},
c: Joi.ref('$x')
});
Joi.validate({ a: 5, b: { c: 5 } }, schema, { context: { x: 5 } }, (err, value) => {});
Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
const ref = Joi.ref('a');
Joi.isRef(ref); // returns true
Get a sub-schema of an existing schema based on a path. Path separator is a dot (.
).
const schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });
const number = Joi.reach(schema, 'foo.bar');
Creates a new Joi instance that will apply defaults onto newly created schemas through the use of the fn
function that takes exactly one argument, the schema being created.
The function must always return a schema, even if untransformed.
const defaultJoi = Joi.defaults((schema) => {
switch (schema.schemaType) {
case 'string':
return schema.allow('');
case 'object':
return schema.min(1);
default:
return schema;
}
});
const schema = defaultJoi.object(); // Equivalent to a Joi.object().min(1)
Creates a new Joi instance customized with the extension(s) you provide included.
It is important to understand that original Joi library is not modified by this.
The extension makes use of some common structures that need to be described prior :
value
- the value being processed by Joi.state
- an object containing the current context of validation.key
- the key of the current value.path
- the full path of the current value.parent
- the potential parent of the current value.
options
- options object provided throughany().options()
orJoi.validate()
.
extension
can be :
- a single extension object
- a factory function generating an extension object
- or an array of those
Extension objects use the following parameters :
name
- name of the new type you are defining, this can be an existing type. Required.base
- an existing Joi schema to base your type upon. Defaults toJoi.any()
.coerce
- an optional function that runs before the base, usually serves when you want to coerce values of a different type than your base. It takes 3 argumentsvalue
,state
andoptions
.pre
- an optional function that runs first in the validation chain, usually serves when you need to cast values. It takes 3 argumentsvalue
,state
andoptions
.language
- an optional object to add error definitions. Every key will be prefixed by the type name.describe
- an optional function taking the fully formed description to post-process it.rules
- an optional array of rules to add.name
- name of the new rule. Required.params
- an optional object containing Joi schemas of each parameter ordered. You can also pass a single Joi schema as long as it is aJoi.object()
, of course some methods such aspattern
orrename
won't be useful or won't work at all in this given context.setup
- an optional function that takes an object with the provided parameters to allow for internals manipulation of the schema when a rule is set, you can optionally return a new Joi schema that will be taken as the new schema instance. At least one ofsetup
orvalidate
must be provided.validate
- an optional function to validate values that takes 4 parametersparams
,value
,state
andoptions
. At least one ofsetup
orvalidate
must be provided.description
- an optional string or function taking the parameters as argument to describe what the rule is doing.
Factory functions are advised if you intend to publish your extensions for others to use, because they are capable of using an extended joi being built, thus avoiding any erasure when using multiple extensions at the same time. See an example of a factory function in the section below.
If you publish your extension on npm, make sure to add joi
and extension
as keywords so that it's discoverable more easily.
const Joi = require('joi');
const customJoi = Joi.extend((joi) => ({
base: joi.number(),
name: 'number',
language: {
round: 'needs to be a rounded number', // Used below as 'number.round'
dividable: 'needs to be dividable by {{q}}'
},
pre(value, state, options) {
if (options.convert && this._flags.round) {
return Math.round(value); // Change the value
}
return value; // Keep the value as it was
},
rules: [
{
name: 'round',
setup(params) {
this._flags.round = true; // Set a flag for later use
},
validate(params, value, state, options) {
if (value % 1 !== 0) {
// Generate an error, state and options need to be passed
return this.createError('number.round', { v: value }, state, options);
}
return value; // Everything is OK
}
},
{
name: 'dividable',
params: {
q: joi.alternatives([joi.number().required(), joi.func().ref()])
},
validate(params, value, state, options) {
if (value % params.q !== 0) {
// Generate an error, state and options need to be passed, q is used in the language
return this.createError('number.dividable', { v: value, q: params.q }, state, options);
}
return value; // Everything is OK
}
}
]
}));
const schema = customJoi.number().round().dividable(3);
Generates a schema object that matches any data type.
const any = Joi.any();
any.validate('a', (err, value) => { });
Gets the type of the schema.
const schema = Joi.string();
schema.schemaType === 'string'; // === true
Validates a value using the schema and options where:
value
- the value being validated.options
- an object with the same optional keys asJoi.validate(value, schema, options, callback)
.callback
- an optional synchronous callback method using the the same signature asJoi.validate(value, schema, options, callback)
.
const schema = Joi.object({
a: Joi.number()
});
const value = {
a: '123'
};
schema.validate(value, (err, value) => { });
// err -> null
// value.a -> 123 (number, not string)
// or
const result = schema.validate(value);
// result.error -> null
// result.value -> { "a" : 123 }
// or
const promise = schema.validate(value);
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.value
can be an array of values, or multiple values can be passed as individual arguments.value
supports references.
Note that this whitelist of allowed values is in addition to any other permitted values.
To create an exclusive whitelist of values, see any.valid(value)
.
const 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.value
can be an array of values, or multiple values can be passed as individual arguments.value
supports references.
const 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.value
can be an array of values, or multiple values can be passed as individual arguments.value
supports references.
const 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.
const schema = 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.
Note: this does not allow a null
value. To do that, use any.allow(value)
. Or both!
const schema = Joi.any().optional();
Marks a key as forbidden which will not allow any value except undefined
. Used to explicitly forbid keys.
const schema = {
a: Joi.any().forbidden()
};
Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
const schema = Joi.object({
username: Joi.string(),
password: Joi.string().strip()
});
schema.validate({ username: 'test', password: 'hunter2' }, (err, value) => {
// value = { username: 'test' }
});
const schema = Joi.array().items(Joi.string(), Joi.any().strip());
schema.validate(['one', 'two', true, false, 1, 2], (err, value) => {
// value = ['one', 'two']
});
Annotates the key where:
desc
- the description string.
const schema = Joi.any().description('this key will match anything you give it');
Annotates the key where:
notes
- the notes string or array of strings.
const schema = Joi.any().notes(['this is special', 'this is important']);
Annotates the key where:
tags
- the tag string or array of strings.
const schema = Joi.any().tags(['api', 'user']);
Attaches metadata to the key where:
meta
- the meta object to attach.
const schema = Joi.any().meta({ index: true });
Annotates the key where:
value
- an example value.
If the example fails to pass validation, the function will throw.
const schema = Joi.string().min(4).example('abcd');
Annotates the key where:
name
- the unit name of the value.
const schema = Joi.number().unit('milliseconds');
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)
.
const schema = Joi.any().options({ convert: false });
Strict mode sets the options.convert
options to false
which prevent type casting for the current key and any child keys.
isStrict
- whether strict mode is enabled or not. Defaults to true.
const schema = Joi.any().strict();
Sets a default value if the original value is undefined where:
value
- the value.value
supports references.value
may also be a function which returns the default value. Ifvalue
is specified as a function that accepts a single parameter, that parameter will be a context object that can be used to derive the resulting value.- Use a function when setting a dynamic value, such as the current time. Ex:
default(Date.now, 'time of creation')
- Caution: this clones the object, which incurs some overhead so if you don't need access to the context define your method so that it does not accept any parameters.
- Use a function when setting a dynamic value, such as the current time. Ex:
- without any
value
,default
has no effect, except forobject
that will then create nested defaults (applying inner defaults of that object).
Note that if value
is an object, any changes to the object after default()
is called will change the reference
and any future assignment.
Additionally, when specifying a method you must either have a description
property on your method or the second parameter is required.
const generateUsername = (context) => {
return context.firstname.toLowerCase() + '-' + context.lastname.toLowerCase();
};
generateUsername.description = 'generated username';
const schema = {
username: Joi.string().default(generateUsername),
firstname: Joi.string(),
lastname: Joi.string(),
created: Joi.date().default(Date.now, 'time of creation'),
status: Joi.string().default('registered')
};
Joi.validate({
firstname: 'Jane',
lastname: 'Doe'
}, schema, (err, value) => {
// value.status === 'registered'
// value.username === 'jane-doe'
// value.created will be the time of validation
});
Returns a new type that is the result of adding the rules of one type to another where:
schema
- a joi type to merge into the current schema. Can only be of the same type as the context type orany
. If applied to anany
type, the schema can be any other schema.
const a = Joi.string().valid('a');
const b = Joi.string().valid('b');
const ab = a.concat(b);
Converts the type into an alternatives
type where the conditions are merged into the type definition where:
condition
- the key name or reference, or a schema.options
- an object with:is
- the required condition joi type. Anything that is not a joi schema will be converted using Joi.compile. Forbidden whencondition
is a schema.then
- the alternative schema type if the condition is true. Required ifotherwise
is missing.otherwise
- the alternative schema type if the condition is false. Required ifthen
is missing.
Note: by default, the is
condition schema allows for undefined
values. Use .required()
to override.
For example, use is: Joi.number().required()
to guarantee that a joi reference exists and is a number.
const schema = {
a: Joi.any().valid('x').when('b', { is: Joi.exist(), then: Joi.valid('y'), otherwise: Joi.valid('z') }),
b: Joi.any()
};
Or with a schema:
const schema = Joi.object({
a: Joi.any().valid('x'),
b: Joi.any()
}).when(Joi.object({ b: Joi.exist() }).unknown(), {
then: Joi.object({
a: Joi.valid('y')
}),
otherwise: Joi.object({
a: Joi.valid('z')
})
});
Note that this style is much more useful when your whole schema depends on the value of one of its property, or if you find yourself repeating the check for many keys of an object.
Alternatively, if you want to specify a specific type such as string
, array
, etc, you can do so like this:
const schema = {
a: Joi.valid('a', 'b', 'other'),
other: Joi.string()
.when('a', { is: 'other', then: Joi.required() }),
};
If you need to validate a child key inside a nested object based on a sibling's value, you can do so like this:
const schema = Joi.object().keys({
a: Joi.boolean().required(),
b: Joi.object()
.keys({
c: Joi.string(),
d: Joi.number().required()
})
.required()
.when('a', {
is: true,
then: Joi.object({ c: Joi.required() }) // b.c is required only when a is true
})
});
If you want to validate one key based on the existence of another key, you can do so like the following (notice the use of required()
):
const schema = Joi.object().keys({
min: Joi.number(),
max: Joi.number().when('min', {
is: Joi.number().required(),
then: Joi.number().greater(Joi.ref('min')),
}),
});
Overrides the key name in error messages.
name
- the name of the key.
const schema = {
first_name: Joi.string().label('First Name')
};
Outputs the original untouched value instead of the casted value.
isRaw
- whether to enable raw mode or not. Defaults to true.
const timestampSchema = Joi.date().timestamp();
timestampSchema.validate('12376834097810'); // { error: null, value: Sat Mar 17 2362 04:28:17 GMT-0500 (CDT) }
const rawTimestampSchema = Joi.date().timestamp().raw();
rawTimestampSchema.validate('12376834097810'); // { error: null, value: '12376834097810' }
Considers anything that matches the schema to be empty (undefined
).
schema
- any object or joi schema to match. An undefined schema unsets that rule.
let schema = Joi.string().empty('');
schema.validate(''); // returns { error: null, value: undefined }
schema = schema.empty();
schema.validate(''); // returns { error: "value" is not allowed to be empty, value: '' }
Overrides the default joi error with a custom error if the rule fails where:
err
can be:- an instance of
Error
- the override error. - a
function(errors)
, taking an array of errors as argument, where it must either:- return a
string
- substitutes the error message with this text - return a single
object
or anArray
of it, where:type
- optional parameter providing the type of the error (eg.number.min
).message
- optional parameter iftemplate
is provided, containing the text of the error.template
- optional parameter ifmessage
is provided, containing a template string, using the same format as usual joi language errors.context
- optional parameter, to provide context to your error if you are using thetemplate
.
- return an
Error
- same as when you directly provide anError
, but you can customize the error message based on the errors.
- return a
- an instance of
Note that if you provide an Error
, it will be returned as-is, unmodified and undecorated with any of the
normal joi error properties. If validation fails and another error is found before the error
override, that error will be returned and the override will be ignored (unless the abortEarly
option has been set to false
).
let schema = Joi.string().error(new Error('Was REALLY expecting a string'));
schema.validate(3); // returns error.message === 'Was REALLY expecting a string'
let schema = Joi.object({
foo: Joi.number().min(0).error(() => '"foo" requires a positive number')
});
schema.validate({ foo: -2 }); // returns error.message === 'child "foo" fails because ["foo" requires a positive number]'
let schema = Joi.object({
foo: Joi.number().min(0).error((errors) => {
return 'found errors with ' + errors.map((err) => `${err.type}(${err.context.limit}) with value ${err.context.value}`).join(' and ');
})
});
schema.validate({ foo: -2 }); // returns error.message === 'child "foo" fails because [found errors with number.min(0) with value -2]'
let schema = Joi.object({
foo: Joi.number().min(0).error((errors) => {
return {
template: 'contains {{errors}} errors, here is the list : {{codes}}',
context: {
errors: errors.length,
codes: errors.map((err) => err.type)
}
};
})
});
schema.validate({ foo: -2 }); // returns error.message === 'child "foo" fails because ["foo" contains 1 errors, here is the list : [number.min]]'
Note that if you want to intercept errors on nested structures such as objects and arrays, you will also get a nested structure to explore the children errors, going one level down through the err.context.reason
property.
If you want a full substitution of the error system, you can hook at the root and render that errors
array with whatever templating system you want, just be aware that you will have to crawl the nested errors for the information you want to actually show.
Generates a schema object that matches an array data type. Note that undefined values inside arrays are not allowed by
default but can be by using sparse()
. If the validation convert
option is on (enabled by default), a string will be
converted to an array
if specified via JSON.parse()
. Also, if convert
array.single()
are both on, then when a
single value is specified it will be converted to an array
.
Supports the same methods of the any()
type.
const array = Joi.array().items(Joi.string().valid('a', 'b'));
array.validate(['a', 'b', 'a'], (err, value) => { });
Allows this array to be sparse. enabled
can be used with a falsy value to go back to the default behavior.
let schema = Joi.array().sparse(); // undefined values are now allowed
schema = schema.sparse(false); // undefined values are now denied
Allows single values to be checked against rules as if it were provided as an array.
enabled
can be used with a falsy value to go back to the default behavior.
const schema = Joi.array().items(Joi.number()).single();
schema.validate([4]); // returns `{ error: null, value: [ 4 ] }`
schema.validate(4); // returns `{ error: null, value: [ 4 ] }`
Lists the types allowed for the array values where:
type
- a joi schema object to validate each array item against.type
can be an array of values, or multiple values can be passed as individual arguments.
If a given type is .required()
then there must be a matching item in the array.
If a type is .forbidden()
then it cannot appear in the array.
Required items can be added multiple times to signify that multiple items must be found.
Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly.
const schema = Joi.array().items(Joi.string(), Joi.number()); // array may contain strings and numbers
const schema = Joi.array().items(Joi.string().required(), Joi.string().required()); // array must contain at least two strings
const schema = Joi.array().items(Joi.string().valid('not allowed').forbidden(), Joi.string()); // array may contain strings, but none of those strings can match 'not allowed'
const schema = Joi.array().items(Joi.string().label('My string').required(), Joi.number().required()); // If this fails it can result in `[ValidationError: "value" does not contain [My string] and 1 other required value(s)]`
Lists the types in sequence order for the array values where:
type
- a joi schema object to validate against each array item in sequence order.type
can be an array of values, or multiple values can be passed as individual arguments.
If a given type is .required()
then there must be a matching item with the same index position in the array.
Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly.
const schema = Joi.array().ordered(Joi.string().required(), Joi.number().required()); // array must have first item as string and second item as number
const schema = Joi.array().ordered(Joi.string().required()).items(Joi.number().required()); // array must have first item as string and 1 or more subsequent items as number
const schema = Joi.array().ordered(Joi.string().required(), Joi.number()); // array must have first item as string and optionally second item as number
Specifies the minimum number of items in the array where:
limit
- the lowest number of array items allowed.
const schema = Joi.array().min(2);
It can also be a reference to another field.
const schema = Joi.object({
limit: Joi.number().integer().required(),
numbers: Joi.array().min(Joi.ref('limit')).required()
});
Specifies the maximum number of items in the array where:
limit
- the highest number of array items allowed.
const schema = Joi.array().max(10);
It can also be a reference to another field.
const schema = Joi.object({
limit: Joi.number().integer().required(),
numbers: Joi.array().max(Joi.ref('limit')).required()
});
Specifies the exact number of items in the array where:
limit
- the number of array items allowed.
const schema = Joi.array().length(5);
It can also be a reference to another field.
const schema = Joi.object({
limit: Joi.number().integer().required(),
numbers: Joi.array().length(Joi.ref('limit')).required()
});
Requires the array values to be unique.
You can provide a custom comparator
that is either :
- a function that takes 2 parameters to compare. This function should return whether the 2 parameters are equal or not, you are also responsible for this function not to fail, any
Error
would bubble out of Joi. - a string in dot notation representing the path of the element to do uniqueness check on. Any missing path will be considered undefined, and can as well only exist once.
Note: remember that if you provide a custom comparator function, different types can be passed as parameter depending on the rules you set on items.
Be aware that a deep equality is performed on elements of the array having a type of object
, a performance penalty is to be expected for this kind of operation.
const schema = Joi.array().unique();
const schema = Joi.array().unique((a, b) => a.property === b.property);
const schema = Joi.array().unique('customer.id');
Generates a schema object that matches a boolean data type. Can also be called via bool()
. If the validation convert
option is on (enabled by default), a string (either "true" or "false") will be converted to a boolean
if specified.
Supports the same methods of the any()
type.
const boolean = Joi.boolean();
boolean.validate(