9.0.1 API Reference

Joi

validate(value, schema, [options], [callback])

Validates a value using the given schema and options where:

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 }

compile(schema)

Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object) where:

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')
        ])
    })
]);

assert(value, schema, [message])

Validates a value against a schema and throws if validation fails where:

Joi.assert('x', Joi.number());

attempt(value, schema, [message])

Validates a value against a schema, returns valid object, and throws if validation fails where:

Joi.attempt('x', Joi.number()); // throws error
const result = Joi.attempt('4', Joi.number()); // result -> 4

ref(key, options)

Creates a reference to another property in the object being validated.

const ref = Joi.ref('#a/b/c', { contextPrefix: '#', separator: '/' });

isRef(ref)

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

reach(schema, path)

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');

extend(extension)

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.

Terms

The extension makes use of some common structures that need to be described prior :

Extension

extension can be a single extension object or an array of extension objects using the following parameters :

Examples

const Joi = require('joi');
const customJoi = Joi.extend({
    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);

any

Generates a schema object that matches any data type.

const any = Joi.any();
any.validate('a', (err, value) => { });

any.allow(value)

Whitelists a value where:

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'])
};

any.valid(value) - aliases: only, equal

Adds the provided values into the allowed whitelist and marks them as the only valid values allowed where:

const schema = {
    a: Joi.any().valid('a'),
    b: Joi.any().valid('b', 'B'),
    c: Joi.any().valid(['c', 'C'])
};

any.invalid(value) - aliases: disallow, not

Blacklists a value where:

const schema = {
    a: Joi.any().invalid('a'),
    b: Joi.any().invalid('b', 'B'),
    c: Joi.any().invalid(['c', 'C'])
};

any.required()

Marks a key as required which will not allow undefined as value. All keys are optional by default.

const schema = Joi.any().required();

any.optional()

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.

const schema = Joi.any().optional();

any.forbidden()

Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.

const schema = {
    a: Joi.any().forbidden()
};

any.strip()

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']
});

any.description(desc)

Annotates the key where:

const schema = Joi.any().description('this key will match anything you give it');

any.notes(notes)

Annotates the key where:

const schema = Joi.any().notes(['this is special', 'this is important']);

any.tags(tags)

Annotates the key where:

const schema = Joi.any().tags(['api', 'user']);

any.meta(meta)

Attaches metadata to the key where:

const schema = Joi.any().meta({ index: true });

any.example(value)

Annotates the key where:

If the example fails to pass validation, the function will throw.

const schema = Joi.string().min(4).example('abcd');

any.unit(name)

Annotates the key where:

const schema = Joi.number().unit('milliseconds');

any.options(options)

Overrides the global validate() options for the current key and any sub-key where:

const schema = Joi.any().options({ convert: false });

any.strict(isStrict)

Strict mode sets the options.convert options to false which prevent type casting for the current key and any child keys.

const schema = Joi.any().strict();

any.default([value, [description]])

Sets a default value if the original value is undefined where:

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
});

any.concat(schema)

Returns a new type that is the result of adding the rules of one type to another where:

const a = Joi.string().valid('a');
const b = Joi.string().valid('b');
const ab = a.concat(b);

any.when(ref, options)

Converts the type into an alternatives type where the conditions are merged into the type definition where:

const schema = {
    a: Joi.any().valid('x').when('b', { is: 5, then: Joi.valid('y'), otherwise: Joi.valid('z') }),
    b: Joi.any()
};

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
        })
});

any.label(name)

Overrides the key name in error messages.

const schema = {
    first_name: Joi.string().label('First Name')
};

any.raw(isRaw)

Outputs the original untouched value instead of the casted value.

const schema = {
    timestamp: Joi.date().format('YYYYMMDD').raw()
};

any.empty(schema)

Considers anything that matches the schema to be empty (undefined).

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: '' }

any.error(err)

Overrides the default joi error with a custom error if the rule fails where:

Note that the provided error 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 err.message === 'Was REALLY expecting a string'

array

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().

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) => { });

array.sparse([enabled])

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

array.single([enabled])

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 ] }`

array.items(type)

Lists the types allowed for the array values where:

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)]`

array.ordered(type)

Lists the types in sequence order for the array values where:

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

array.min(limit)

Specifies the minimum number of items in the array where:

const schema = Joi.array().min(2);

array.max(limit)

Specifies the maximum number of items in the array where:

const schema = Joi.array().max(10);

array.length(limit)

Specifies the exact number of items in the array where:

const schema = Joi.array().length(5);

array.unique([comparator])

Requires the array values to be unique.

You can provide a custom comparator 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.

Note: remember that if you provide a custom comparator, 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);

boolean

Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', 'no', 'on', 'off', 1, 0, '1', or '0'). Can also be called via bool().

Supports the same methods of the any() type.

const boolean = Joi.boolean();
boolean.validate(true, (err, value) => { });

binary

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.

const schema = Joi.binary();

binary.encoding(encoding)

Sets the string encoding format if a string input is converted to a buffer where:

const schema = Joi.binary().encoding('base64');

binary.min(limit)

Specifies the minimum length of the buffer where:

const schema = Joi.binary().min(2);

binary.max(limit)

Specifies the maximum length of the buffer where:

const schema = Joi.binary().max(10);

binary.length(limit)

Specifies the exact length of the buffer:

const schema = Joi.binary().length(5);

date

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.

const date = Joi.date();
date.validate('12-21-2012', (err, value) => { });

date.min(date)

Specifies the oldest date allowed where:

const schema = Joi.date().min('1-1-1974');

Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future.

const schema = Joi.date().min('now');

It can also be a reference to another field.

const schema = Joi.object({
  from: Joi.date().required(),
  to: Joi.date().min(Joi.ref('from')).required()
});

date.max(date)

Specifies the latest date allowed where:

const schema = Joi.date().max('12-31-2020');

Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future.

const schema = Joi.date().max('now');

It can also be a reference to another field.

const schema = Joi.object({
  from: Joi.date().max(Joi.ref('to')).required(),
  to: Joi.date().required()
});

date.format(format)

Specifies the allowed date format:

const schema = Joi.date().format('YYYY/MM/DD');

date.iso()

Requires the string value to be in valid ISO 8601 date format.

const schema = Joi.date().iso();

date.timestamp([type])

Requires the value to be a timestamp interval from Unix Time.

const schema = Joi.date().timestamp(); // defaults to javascript timestamp
const schema = Joi.date().timestamp('javascript'); // also, for javascript timestamp (milliseconds)
const schema = Joi.date().timestamp('unix'); // for unix timestamp (seconds)

func

Generates a schema object that matches a function type.

Supports the same methods of the object() type. Note that validating a function keys will cause the function to be cloned. While the function will retain its prototype and closure, it will lose its length property value (will be set to 0).

const func = Joi.func();
func.validate(function () {}, (err, value) => { });

func.arity(n)

Specifies the arity of the function where:

const schema = Joi.func().arity(2);

func.minArity(n)

Specifies the minimal arity of the function where:

const schema = Joi.func().minArity(1);

func.maxArity(n)

Specifies the maximal arity of the function where:

const schema = Joi.func().arity(3);

func.ref()

Requires the function to be a Joi reference.

const schema = Joi.func().ref();

number

Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).

Infinity and -Infinity are invalid by default, you can change that behavior by calling allow(Infinity, -Infinity).

Supports the same methods of the any() type.

const number = Joi.number();
number.validate(5, (err, value) => { });

number.min(limit)

Specifies the minimum value where:

const schema = Joi.number().min(2);

It can also be a reference to another field.

const schema = Joi.object({
  min: Joi.number().required(),
  max: Joi.number().min(Joi.ref('min')).required()
});

number.max(limit)

Specifies the maximum value where:

const schema = Joi.number().max(10);

It can also be a reference to another field.

const schema = Joi.object({
  min: Joi.number().max(Joi.ref('max')).required(),
  max: Joi.number().required()
});

number.greater(limit)

Specifies that the value must be greater than limit.

const schema = Joi.number().greater(5);
const schema = Joi.object({
  min: Joi.number().required(),
  max: Joi.number().greater(Joi.ref('min')).required()
});

number.less(limit)

Specifies that the value must be less than limit.

const schema = Joi.number().less(10);

It can also be a reference to another field.

const schema = Joi.object({
  min: Joi.number().less(Joi.ref('max')).required(),
  max: Joi.number().required()
});

number.integer()

Requires the number to be an integer (no floating point).

const schema = Joi.number().integer();

number.precision(limit)

Specifies the maximum number of decimal places where:

const schema = Joi.number().precision(2);

number.multiple(base)

Specifies that the value must be a multiple of base:

const schema = Joi.number().multiple(3);

Notes: Joi.number.multiple(base) uses the modulo operator (%) to determine if a number is multiple of another number. Therefore, it has the normal limitations of Javascript modulo operator. The results with decimal/floats maybe incorrect.

number.positive()

Requires the number to be positive.

const schema = Joi.number().positive();

number.negative()

Requires the number to be negative.

const schema = Joi.number().negative();

object

Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). Defaults to allowing any child key.

Supports the same methods of the any() type.

const object = Joi.object().keys({
    a: Joi.number().min(1).max(10).integer(),
    b: 'some string'
});

object.validate({ a: 5 }, (err, value) => { });

object.keys([schema])

Sets or extends the allowed object keys where:

const base = Joi.object().keys({
    a: Joi.number(),
    b: Joi.string()
});
// Validate keys a, b and c.
const extended = base.keys({
    c: Joi.boolean()
});

Notes: We have three different ways to define a schema for performing a validation

const schema = {
    a: Joi.string(),
    b: Joi.number()
};
const schema = Joi.object({
    a: Joi.string(),
    b: Joi.number()
});
const schema = Joi.object().keys({
    a: Joi.string(),
    b: Joi.number()
});

While all these three objects defined above will result in the same validation object, there are some differences in using one or another:

{} notation

When using the {} notation, you are just defining a plain JS object, which isn't a schema object. You can pass it to the validation method but you can't call validate() method of the object because it's just a plain JS object.

Besides, passing the {} object to the validate() method each time, will perform an expensive schema compilation operation on every validation.

Joi.object([schema]) notation

Using Joi.object([schema]) will return a schema object, so you can call the validate() method directly, e.g:

const schema = Joi.object({
    a: Joi.boolean()
});

schema.validate(true, (err, value) => {
    console.log('err: ', err);
});

When you use Joi.object([schema]), it gets compiled the first time, so you can pass it to the validate() method multiple times and no overhead is added.

Another benefits of using Joi.object([schema]) instead of a plain JS object is that you can set any options on the object like allowing unknown keys, e.g:

const schema = Joi.object({
    arg: Joi.string().valid('firstname', 'lastname', 'title', 'company', 'jobtitle'),
    value: Joi.string(),
}).pattern(/firstname|lastname/, Joi.string().min(2));
Joi.object().keys([schema]) notation

This is basically the same as Joi.object([schema]), but using Joi.object().keys([schema]) is more useful when you want to add more keys (e.g. call keys() multiple times). If you are only adding one set of keys, you can skip the keys() method and just use object() directly.

Some people like to use keys() to make the code more explicit (this is style only).

object.min(limit)

Specifies the minimum number of keys in the object where:

const schema = Joi.object().min(2);

object.max(limit)

Specifies the maximum number of keys in the object where:

const schema = Joi.object().max(10);

object.length(limit)

Specifies the exact number of keys in the object where:

const schema = Joi.object().length(5);

object.pattern(regex, schema)

Specify validation rules for unknown keys matching a pattern where:

const schema = Joi.object({
    a: Joi.string()
}).pattern(/\w\d/, Joi.boolean());

object.and(peers)

Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well where:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).and('a', 'b');

object.nand(peers)

Defines a relationship between keys where not all peers can be present at the same time where:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).nand('a', 'b');

object.or(peers)

Defines a relationship between keys where one of the peers is required (and more than one is allowed) where:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).or('a', 'b');

object.xor(peers)

Defines an exclusive relationship between a set of keys where one of them is required but not at the same time where:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).xor('a', 'b');

object.with(key, peers)

Requires the presence of other keys whenever the specified key is present where:

Note that unlike object.and(), with() creates a dependency only between the key and each of the peers, not between the peers themselves.

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).with('a', 'b');

object.without(key, peers)

Forbids the presence of other keys whenever the specified is present where:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any()
}).without('a', ['b']);

object.rename(from, to, [options])

Renames a key to another name (deletes the renamed key) where:

Keys are renamed before any other validation rules are applied.

const object = Joi.object().keys({
    a: Joi.number()
}).rename('b', 'a');

object.validate({ b: 5 }, (err, value) => { });

object.assert(ref, schema, [message])

Verifies an assertion where:

const schema = Joi.object().keys({
    a: {
        b: Joi.string(),
        c: Joi.number()
    },
    d: {
        e: Joi.any()
    }
}).assert('d.e', Joi.ref('a.c'), 'equal to a.c');

object.unknown([allow])

Overrides the handling of unknown keys for the scope of the current object only (does not apply to children) where:

const schema = Joi.object({ a: Joi.any() }).unknown();

object.type(constructor, [name])

Requires the object to be an instance of a given constructor where:

const schema = Joi.object().type(RegExp);

object.schema()

Requires the object to be a Joi schema instance.

const schema = Joi.object().schema();

object.requiredKeys(children)

Sets the specified children to required.

const schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } });
const requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d');

Note that in this example '' means the current object, a is not required but b is, as well as c and d.

object.optionalKeys(children)

Sets the specified children to optional.

const schema = Joi.object().keys({ a: { b: Joi.number().required() }, c: { d: Joi.string().required() } });
const requiredSchema = schema.optionalKeys('a.b', 'c.d');

The behavior is exactly the same as requiredKeys.

string

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.

const schema = Joi.string().min(1).max(10);
schema.validate('12345', (err, value) => { });

string.insensitive()

Allows the value to match any whitelist of blacklist item in a case insensitive comparison.

const schema = Joi.string().valid('a').insensitive();

string.min(limit, [encoding])

Specifies the minimum number string characters where:

const schema = Joi.string().min(2);

It can also be a reference to another field.

const schema = Joi.object({
  min: Joi.string().required(),
  value: Joi.string().min(Joi.ref('min'), 'utf8').required()
});

string.max(limit, [encoding])

Specifies the maximum number of string characters where:

const schema = Joi.string().max(10);

It can also be a reference to another field.

const schema = Joi.object({
  max: Joi.string().required(),
  value: Joi.string().max(Joi.ref('max'), 'utf8').required()
});

string.truncate([enabled])

Specifies whether the string.max() limit should be used as a truncation.

Parameters are:

const schema = Joi.string().max(5).truncate();

string.creditCard()

Requires the number to be a credit card number (Using Lunh Algorithm).

const schema = Joi.string().creditCard();

string.length(limit, [encoding])

Specifies the exact string length required where:

const schema = Joi.string().length(5);

It can also be a reference to another field.

const schema = Joi.object({
  length: Joi.string().required(),
  value: Joi.string().length(Joi.ref('length'), 'utf8').required()
});

string.regex(pattern, [name])

Defines a regular expression rule where:

const schema = Joi.string().regex(/^[abc]+$/);

string.replace(pattern, replacement)

Replace characters matching the given pattern with the specified replacement string where:

const schema = Joi.string().replace(/b/gi, 'x');
schema.validate('abBc', (err, value) => {
  // here value will be 'axxc'
});

When pattern is a string all its occurrences will be replaced.

string.alphanum()

Requires the string value to only contain a-z, A-Z, and 0-9.

const schema = Joi.string().alphanum();

string.token()

Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.

const schema = Joi.string().token();

string.email([options])

Requires the string value to be a valid email address.

const schema = Joi.string().email();

string.ip([options])

Requires the string value to be a valid ip address.

// Accept only ipv4 and ipv6 addresses with a CIDR
const schema = Joi.string().ip({
  version: [
    'ipv4',
    'ipv6'
  ],
  cidr: 'required'
});

string.uri([options])

Requires the string value to be a valid RFC 3986 URI.

// Accept git or git http/https
const schema = Joi.string().uri({
  scheme: [
    'git',
    /git\+https?/
  ]
});

string.guid()

Requires the string value to be a valid GUID.

const schema = Joi.string().guid();

string.hex()

Requires the string value to be a valid hexadecimal string.

const schema = Joi.string().hex();

string.hostname()

Requires the string value to be a valid hostname as per RFC1123.

const schema = Joi.string().hostname();

string.lowercase()

Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.

const schema = Joi.string().lowercase();

string.uppercase()

Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.

const schema = Joi.string().uppercase();

string.trim()

Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.

const schema = Joi.string().trim();

string.isoDate()

Requires the string value to be in valid ISO 8601 date format.

const schema = Joi.string().isoDate();

alternatives

Generates a type that will match one of the provided alternative schemas via the try() method. If no schemas are added, the type will not match any value except for undefined.

Supports the same methods of the any() type.

Alternatives can be expressed using the shorter [] notation.

const alt = Joi.alternatives().try(Joi.number(), Joi.string());
// Same as [Joi.number(), Joi.string()]

alternatives.try(schemas)

Adds an alternative schema type for attempting to match against the validated value where:

const alt = Joi.alternatives().try(Joi.number(), Joi.string());
alt.validate('a', (err, value) => { });

alternatives.when(ref, options)

Adds a conditional alternative schema type based on another key (not the same as any.when()) value where:

const schema = {
    a: Joi.alternatives().when('b', { is: 5, then: Joi.string(), otherwise: Joi.number() }),
    b: Joi.any()
};

Note that when() only adds additional alternatives to try and does not impact the overall type. Setting a required() rule on a single alternative will not apply to the overall key. For example, this definition of a:

const schema = {
    a: Joi.alternatives().when('b', { is: true, then: Joi.required() }),
    b: Joi.boolean()
};

Does not turn a into a required key when b is true. Instead, it tells the validator to try and match the value to anything that's not undefined. However, since Joi.alternatives() by itself allows undefined, the rule does not accomplish turning a to a required value. This rule is the same as Joi.alternatives([Joi.required()]) when b is true which will allow any value including undefined.

To accomplish the desired result above use:

const schema = {
    a: Joi.when('b', { is: true, then: Joi.required() }),
    b: Joi.boolean()
};

lazy(fn)

Generates a placeholder schema for a schema that you would provide with the fn.

Supports the same methods of the any() type.

This is mostly useful for recursive schemas, like :

const Person = Joi.object({
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    children: Joi.array().items(Joi.lazy(() => Person).description('Person schema'))
});

ref(key, [options])

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:

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) => {});

Errors

Joi throws classical javascript Errors containing :