joi / latest

Introduction

joi lets you describe your data using a simple, intuitive, and readable language.

Example

const Joi = require('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}$')),

    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 });
// -> { value: { username: 'abc', birth_year: 1994 } }

schema.validate({});
// -> { value: {}, error: '"username" is required' }

// Also -

try {
    const value = await schema.validateAsync({ 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

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

If the input is valid, then the error will be undefined. 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) 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); // validates fine

    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);
    // or
    Joi.string().validate(undefined, /* options */ { 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.

assert(value, schema, [message], [options])

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 using Joi.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.
  • options - optional options object, passed in to any.validate
Joi.assert('x', Joi.number());

attempt(value, schema, [message], [options])

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 using Joi.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.
  • options - optional options object, passed in to any.validate
Joi.attempt('x', Joi.number()); // throws error
const result = Joi.attempt('4', Joi.number()); // result -> 4

cache.provision([options])

Provisions a simple LRU cache for caching simple inputs (undefined, null, strings, numbers, and booleans) where:

  • options - optional settings:
    • max - number of items to store in the cache before the least used items are dropped. Defaults to 1000.

checkPreferences(prefs)

Checks if the provided preferences are valid where:

  • prefs - the preferences object to validate.

Throws an exception if the prefs object is invalid.

The method is provided to perform inputs validation for the any.validate() and any.validateAsync() methods. Validation is not performed automatically for performance reasons. Instead, manually validate the preferences passed once and reuse.

compile(schema, [options])

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.
  • options - optional settings:
    • legacy - if true and the provided schema is (or contains parts) using an older version of joi, will return a compiled schema that is compatible with the older version. If false, the schema is always compiled using the current version and if older schema components are found, an error is thrown.
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({
        a: Joi.boolean().valid(true),
        b: Joi.alternatives().try(
            Joi.string().pattern(/^a/),
            Joi.string().valid('boom')
        )
    })
);

defaults(modifier)

Creates a new joi instance that applies the provided modifier function to every new schemas where:

  • modifier - a function with signature function(schema) that must return a schema object.
const custom = Joi.defaults((schema) => {

    switch (schema.type) {
        case 'string':
            return schema.allow('');
        case 'object':
            return schema.min(1);
        default:
            return schema;
    }
});

const schema = custom.object();   // Returns Joi.object().min(1)

expression(template, [options]) - aliases: x

Generates a dynamic expression using a template string where:

  • template - the template string using the template syntax.
  • options - optional settings used when creating internal references. Supports the same options as ref().

Template syntax

The template syntax uses {} and {{}} enclosed formulas to reference values as well as perform number and string operations. Single braces {} leave the formula result as-is, while double braces {{}} HTML-escape the formula result (unless the template is used for error messages and the errors.escapeHtml preference flag is set to false).

If the formula is a single reference prefixed with : (e.g. {:#ref} or {{:#ref}}), its values will be wrapped according to the wrap validation setting. The #label variable is always wrapped according to the wrap setting.

The formula uses a simple mathematical syntax such as a + b * 2 where the named formula variables are references. Most references can be used as-is but some can create ambiguity with the formula syntax and must be enclosed in [] braces (e.g. [.]).

The formulas can only operate on null, booleans, numbers, and strings. If any operation involves a string, all other numbers will be casted to strings (as the internal implementation uses simple JavaScript operators). The supported operators are: ^, *, /, %, +, -, <, <=, >, >=, ==, !=, &&, ||, and ?? (in this order of precedence).

The reference names can have one of the following prefixes:

  • # - indicates the variable references a local context value. For example, in errors this is the error context, while in rename operations, it is the regular expression matching groups.
  • $ - indicates the variable references a global context value from the context preference object provided as an option to the validation function or set using any.prefs().
  • any other variable references a key within the current value being validated.

The formula syntax also supports built-in functions:

  • if(condition, then, otherwise) - returns then when condition is truthy, otherwise otherwise.
  • length(item) - return the length of an array or string, the number of keys of an object, otherwise null.
  • msg(code) - embeds another error code message.
  • number(value) - cast value to a number.

And the following constants:

  • null
  • true
  • false

extend(...extensions)

Creates a new customized instance of the joi module where:

  • extensions - the extensions configurations as described in Extensions.

Note that the original joi module is not modified by this.

in(ref, [options])

Creates a reference that when resolved, is used as an array of values to match against the rule, where:

Can only be used in rules that support in-references.

const schema = Joi.object({
    a: Joi.array().items(Joi.number()),
    b: Joi.number().valid(Joi.in('a'))
});

isError(err)

Checks whether or not the provided argument is a validation error.

Joi.isError(new Error()); // returns false

isExpression(expression)

Checks whether or not the provided argument is an expression.

const expression = Joi.x('{a}');
Joi.isExpression(expression); // returns true

isRef(ref)

Checks whether or not the provided argument is a reference. Useful if you want to post-process error messages.

const ref = Joi.ref('a');
Joi.isRef(ref); // returns true

isSchema(schema, [options])

Checks whether or not the provided argument is a joi schema where:

  • schema - the value being checked.
  • options - optional settings:
    • legacy - if true, will identify schemas from older versions of joi, otherwise will throw an error. Defaults to false.
const schema = Joi.any();
Joi.isSchema(schema); // returns true

override

A special value used with any.allow(), any.invalid(), and any.valid() as the first value to reset any previously set values.

Joi.valid(1).valid(Joi.override, 2);

// Same as:

Joi.valid(2);

// Whereas:

Joi.valid(1).valid(2);

// Is the same as:

Joi.valid(1, 2);

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:

  • key - the reference target. References can point to sibling keys (a.b) or ancestor keys (...a.b) using the . separator. If a key starts with $ is signifies a context reference which is looked up in the context option object. The key can start with one or more separator characters to indicate a relative starting point.
  • options - optional settings:
    • adjust - a function with the signature function(value) where value is the resolved reference value and the return value is the adjusted value to use. For example (value) => value + 5 will add 5 to the resolved value. Note that the adjust feature will not perform any type validation on the adjusted value and it must match the value expected by the rule it is used in. Cannot be used with map.
    • map - an array of array pairs using the format [[key, value], [key, value]] used to maps the resolved reference value to another value. If the resolved value is not in the map, it is returned as-is. Cannot be used with adjust.
    • prefix - overrides default prefix characters key string prefix. Can be set to false to disable all prefix parsing (treat keys as literal strings), or an object with specific overrides for:
      • global - references to the globally provided context preference. Defaults to '$'.
      • local - references to error-specific or rule specific context. Defaults to '#'.
      • root - references to the root value being validated. Defaults to '/'.
    • separator - overrides the default . hierarchy separator. Set to false to treat the key as a literal value.
    • ancestor - if set to a number, sets the reference relative starting point. Cannot be combined with separator prefix characters. Defaults to the reference key prefix (or 1 if none present).
    • in - creates an in-reference.
    • iterables - when true, the reference resolves by reaching into maps and sets.
    • render - when true, the value of the reference is used instead of its name in error messages and template rendering. Defaults to false.

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({
    a: Joi.ref('b.c'),
    b: {
        c: Joi.any()
    },
    c: Joi.ref('$x')
});

await schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } });

Relative references

By default, a reference is relative to the parent of the current value (the reference key is lookup up inside the parent). This means that in the schema:

{
    x: {
        a: Joi.any(),
        b: {
            c: Joi.any(),
            d: Joi.ref('c')
        }
    },
    y: Joi.any()
}

The reference Joi.ref('c') points to c which is a sibling of d - the reference starting point is d's parent which is b. This schema means that d must be equal to c.

In order to reference a parent peer, you can use a separator prefix where (using . as separator):

  • . - self
  • .. - parent (same as no prefix)
  • ... - grandparent
  • .... - great-grandparent
  • etc.

For example:

{
    x: {
        a: Joi.any(),
        b: {
            c: Joi.any(),
            d: Joi.ref('c'),
            e: Joi.ref('...a'),
            f: Joi.ref('....y')
        }
    },
    y: Joi.any()
}

Another way to specify the relative starting point is using the ancestor option where:

  • 0 - self
  • 1 - parent (this is the default value if no key prefix is present)
  • 2 - grandparent
  • 3 - great-grandparent
  • etc.

For example:

{
    x: {
        a: Joi.any(),
        b: {
            c: Joi.any(),
            d: Joi.ref('c', { ancestor: 1 }),
            e: Joi.ref('a', { ancestor: 2 }),
            f: Joi.ref('y', { ancestor: 3 })
        }
    },
    y: Joi.any()
}

Note that if a reference tries to reach beyond the value root, validation fails.

To specify an absolute path from the value root, use the / prefix:

{
    x: {
        a: Joi.any(),
        b: {
            c: Joi.ref('/x.a')
        }
    }
}

version

Property showing the current version of joi being used.

types()

Returns an object where each key is a plain joi schema type. Useful for creating type shortcuts using deconstruction. Note that the types are already formed and do not need to be called as functions (e.g. string, not string()).

const Joi = require('joi');
const { object, string } = Joi.types();

const schema = object.keys({
  property: string.min(4)
});

any

Generates a schema object that matches any data type.

const any = Joi.any();
await any.validateAsync('a');

any.type

Gets the type of the schema.

const schema = Joi.string();

schema.type === 'string';   // === true

any.allow(...values)

Allows values where:

  • values - one or more allowed values which can be of any type and will be matched against the validated value before applying any other rules. Supports references and in-references. If the first value is Joi.override, will override any previously set values.

Note that this list of allowed values is in addition to any other permitted values. To create an exclusive list of values, see any.valid(value).

const schema = {
    a: Joi.any().allow('a'),
    b: Joi.any().allow('b', 'B')
};

any.alter(targets)

Assign target alteration options to a schema that are applied when any.tailor() is called where:

  • targets - an object where each key is a target name, and each value is a function with signature function(schema) that returns a schema.
const schema = Joi.object({
    key: Joi.string()
        .alter({
            get: (schema) => schema.required(),
            post: (schema) => schema.forbidden()
        })  
});

const getSchema = schema.tailor('get');
const postSchema = schema.tailor('post');

any.artifact(id)

Assigns the schema an artifact id which is included in the validation result if the rule passed validation where:

  • id - any value other than undefined which will be returned as-is in the result artifacts map.
const schema = {
    a: [
        Joi.number().max(10).artifact('under'),
        Joi.number().min(11).artifact('over')
    ]
};

any.cache([cache])

Adds caching to the schema which will attempt to cache the validation results (success and failures) of incoming inputs where:

  • cache - an optional cache implementation compatible with the built-in cache provided by cache.provision(). If no cache is passed, a default cache is provisioned by using cache.provision() internally.

Note that deciding which inputs to cache is left to the cache implementation. The built-in cache will only store simple values such as undefined, null, strings, numbers, and booleans. Any changes to the schema after any.cache() is called will disable caching on the resulting schema. this means that if .cache() is not the last statement in a schema definition, caching will be disabled.

To disable caching for an entire schema in runtime, pass the cache preference set to false.

Caching ignores changes to runtime preference. This means that if you run schema.validate() onces using one set of preferences, and then again using another set (for example, changing the language), the cached results will be based on the first set of preferences.

Before using caching, it is recommended to consider the performance gain as it will not speed up every schema. Schemas using .valid() list will not benefit from caching.

Caching will be ignored when the schema uses references outside of the value scope.

Cache interface

Custom cache implementation must implement the following interface:

class {
    set(key, value) {}
    get(key) { return found ? value : undefined; }
}

Note that key and value can be anything including objects, array, etc. It is recommended to limit the size of the cache when validating external data in order to prevent an attacker from increasing the process memory usage by sending large amount of different data to validate.

any.cast(to)

Casts the validated value to the specified type where:

  • to - the value target type. Each joi schema type supports its own set of cast targets:
    • 'map' - supported by the Joi.object() type, converts the result to a Map object containing the object key-value pairs.
    • 'number' - supported by Joi.boolean() and Joi.date(), converts the result to a number. For dates, number of milliseconds since the epoch and for booleans, 0 for false and 1 for true.
    • 'set' - supported by the Joi.array() type, converts the result to a Set object containing the array values.
    • 'string' - supported by Joi.binary(), Joi.boolean(), Joi.date(), and Joi.number(), converts the result to a string.

any.concat(schema)

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 or any. If applied to an any 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);

any.custom(method, [description])

Adds a custom validation function to execute arbitrary code where:

  • method - the custom (synchronous only) validation function using signature function(value, helpers) where:
    • value - the value being validated.
    • helpers - an object with the following helpers:
      • schema - the current schema.
      • state - the current validation state.
      • prefs - the current preferences.
      • original - the original value passed into validation before any conversions.
      • error(code, [local]) - a method to generate error codes using a message code and optional local context.
      • message(messages, [local]) - a method to generate an error with an internal 'custom' error code and the provided messages object to use as override. Note that this is much slower than using the preferences messages option but is much simpler to write when performance is not important.
      • warn(code, [local]) - a method to add a warning using a message code and optional local context.

Note: if the method fails to return a value, the value will be unset or returned as undefined.

const method = (value, helpers) => {

    // Throw an error (will be replaced with 'any.custom' error)
    if (value === '1') {
        throw new Error('nope');
    }

    // Replace value with a new value
    if (value === '2') {
        return '3';
    }

    // Use error to return an existing error code
    if (value === '4') {
        return helpers.error('any.invalid');
    }

    // Override value with undefined to unset
    if (value === '5') {
        return undefined;
    }

    // Return the value unchanged
    return value;
};

const schema = Joi.string().custom(method, 'custom validation');

Possible validation errors: any.custom

any.default([value])

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

  • value - the default value. One of:
    • a literal value (string, number, object, etc.).
    • a references.
    • a function which returns the default value using the signature function(parent, helpers) where:
      • parent - a clone of the object containing the value being validated. Note that since specifying a parent argument performs cloning, do not declare format arguments if you are not using them.
      • helpers - same as those described in any.custom().

When called without any value on an object schema type, a default value will be automatically generated based on the default values of the object keys.

Note that if value is an object, any changes to the object after default() is called will change the reference and any future assignment. Use a function when setting a dynamic value (e.g. the current time).

const generateUsername = (parent, helpers) => {

  return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase();
};

generateUsername.description = 'generated username';

const schema = Joi.object({
    username: Joi.string().