joi Agent Skills & AI Rules

GitHub

The most powerful data validation library for JS

21,164 stars JavaScript JavaScript 2 files ยท ~243 tokens #hapi#javascript#schema#validation
RAW Rules
1 Discovered Rules โ€ข ~11,985 Estimated Tokens
Loading skill content...

API Interface Contract & Specifications

API.md project-spec ~11,985 tokens
Raw

### Introduction

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

#### Example

```js
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:

```js
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:

```js
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`](#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:

```js
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:

```js
const schema = Joi.object().keys({
    a: Joi.string()
});
```

When validating a schema:

* Values (or keys in case of objects) are optional by default.

    ```js
    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`:

    ```js
    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](#errors) 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`](#compileschema-options) (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`](#anyvalidatevalue-options)

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

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

Validates a value against a schema, returns valid object, and [throws](#errors) 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`](#compileschema-options) (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`](#anyvalidatevalue-options)

```js
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()`](#anyvalidatevalue-options)
and [`any.validateAsync()`](#anyvalidateasyncvalue-options) 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.

```js
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.

```js
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](#template-syntax).
- `options` - optional settings used when creating internal references. Supports the same options
  as [`ref()`](#refkey-options), in addition to those options:
  - `functions` - an object with keys being function names and values being their implementation that will be executed when used in the expression. Using the same name as a built-in function will result in a local override. Note: carefully check your arguments depending on the situation where the expression is used.

#### 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`](#anyvalidatevalue-options) 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()`](#anyprefsoptions--aliases-preferences-options).
- 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](#extensions).

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

### `in(ref, [options])`

Creates a [reference](#refkey-options) that when resolved, is used as an array of values to match against the rule, where:
- `ref` - same as [`Joi.ref()`](#refkey-options).
- `options` - same as [`Joi.ref()`](#refkey-options).

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

```js
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.

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

### `isExpression(expression)`

Checks whether or not the provided argument is an expression.

```js
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.

```js
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`.

```js
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.

```js
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](#Relative-references).
- `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](#Relative-references). Cannot be combined with separator prefix characters. Defaults to the reference key prefix (or `1` if none present).
    - `in` - creates an [in-reference](#inref-options).
    - `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()`](#objectassertref-schema-message).

```js
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:

```js
{
    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:

```js
{
    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:

```js
{
    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:

```js
{
    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()`).

```js
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.

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

#### `any.type`

Gets the type of the schema.

```js
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](#refkey-options) and [in-references](#inref-options). If the first value is [`Joi.override`](#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)`](#anyvalidvalues---aliases-equal).

```js
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()`](#anytailortargets)
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.

```js
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.

```js
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()`](#cacheprovisionoptions). If no `cache` is passed, a default cache
  is provisioned by using [`cache.provision()`](#cacheprovisionoptions) 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:

```js
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.

```js
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], [localState])` - a method to generate error codes using a message code, optional local context and optional validation local state.
        - `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`.

```js
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`](#anycustom)

#### `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](#refkey-options).
    - 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()`](#anycustommethod_description).

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

```js
const generateUsername = (parent, helpers) => {

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

generateUsername.description = 'generated username';

const schema = Joi.object({
    username: Joi.string().default(generateUsername),
    firstname: Joi.string(),
    lastname: Joi.string(),
    created: Joi.date().default(Date.now),
    status: Joi.string().default('registered')
});

const { value } = schema.validate({
    firstname: 'Jane',
    lastname: 'Doe'
});

// value.status === 'registered'
// value.username === 'jane-doe'
// value.created will be the time of validation
```

Possible validation errors: [`any.default`](#anydefault)

#### `any.describe()`

Returns an object that represents the internal configuration of the schema. Useful for debugging
and exposing a schema's configuration to other systems, like valid values in a user interface.

```js
const schema = Joi.any().valid('foo', 'bar');
console.log(schema.describe());
```

Results in:

```
{ type: 'any',
  flags: { only: true },
  valids: [ 'foo', 'bar' ] }
```

#### `any.description(desc)`

Annotates the key where:
- `desc` - the description string.

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

#### `any.empty(schema)`

Considers anything that matches the schema to be empty (`undefined`). Overrides any previous calls to empty.
- `schema` - an object, value, or **joi** schema to match or an array of objects, values, and **joi** schemas to match. An undefined schema unsets that rule.

```js
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:
- `err` can be:
  - an instance of `Error` - the override error.
  - a function with the signature `function(errors)`, where `errors` is an array of validation reports and it returns either a single `Error` or an array of validation reports.

Do not use this method if you are simply trying to override the error message - use `any.message()` or `any.messages()` instead. This method is designed to override the **joi** validation error and return the exact override provided. It is useful when you want to return the result of validation directly (e.g. when using with a **hapi** server) and want to return a different HTTP error code than 400.

Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the normal 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`). If you set multiple errors on a single schema, only the last error is used.

```js
const schema = Joi.string().error(new Error('Was REALLY expecting a string'));
schema.validate(3);     // returns Error('Was REALLY expecting a string')
```

```js
const schema = Joi.object({
    foo: Joi.number().min(0).error((errors) => new Error('"foo" requires a positive number'))
});
schema.validate({ foo: -2 });    // returns new Error('"foo" requires a positive number')
```

```js
const schema = Joi.object({
    foo: Joi.number().min(0).error((errors) => {

        return new Error('found errors with ' + errors.map((err) => `${err.local.key}(${err.local.limit}) with value ${err.local.value}`).join(' and '));
    })
});
schema.validate({ foo: -2 });    // returns new Error('found errors with foo(0) with value -2')
```

#### `any.example(example, [options])`

Adds examples to the schema where:
- `example` - adds an example. Note that no validation is performed on the value.
- `options` - optional settings:
    - `override` - if `true`, replaces any existing examples. Defaults to `false`.

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

#### `any.external(method, [description])`

Adds an external validation rule where:
- `method` - an async or sync function with signature `function(value, helpers)` which can either
  return a replacement value, `undefined` to indicate no change, or throw an error, where:
    - `value` - a clone of the object containing the value being validated.
    - `helpers` - an object with the following helpers:
        - `schema` - the current schema.
        - `linked` - if the schema is a link, the schema it links to.
        - `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 `'external'` 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.
- `description` - optional string used to document the purpose of the method.

Note that external validation rules are only called after the all other validation rules for the
entire schema (from the value root) are checked. This means that any changes made to the value by
the external rules are not available to any other validation rules during the non-external
validation phase.

If schema validation failed, no external validation rules are called.

#### `any.extract(path)`

Returns a sub-schema based on a path of object keys or schema ids where:
- `path` - a dot `.` separated path string or a pre-split array of path keys. The keys must match
  the sub-schema id or object key (if no id was explicitly set).

```js
const schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });
const number = schema.extract('foo.bar');

//or
const result = schema.extract(['foo', 'bar']); //same as number
```

#### `any.failover(value)`

Sets a failover value if the original value fails passing validation where:
- `value` - the failover value. `value` supports [references](#refkey-options). `value` may be
  assigned a function which returns the default value. If `value` 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.

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

Using a function with a single argument performs some internal cloning which has a performance
impact. If you do not need access to the context, define the function without any arguments.

Possible validation errors: [`any.failover`](#anyfailover)

#### `any.forbidden()`

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

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

Possible validation errors: [`any.unknown`](#anyunknown)

#### `any.fork(paths, adjuster)`

Returns a new schema where each of the path keys listed have been modified where:
- `paths` - an array of key strings, a single key string, or an array of arrays of pre-split
  key strings. Key string paths use dot `.` to indicate key hierarchy.
- `adjuster` - a function using the signature `function(schema)` which must return a modified
  schema. For example, `(schema) => schema.required()`.

The method does not modify the original schema.

#### `any.id(id)`

Sets a schema id for reaching into the schema via [`any.extract()`](#anyextractpath) where:
- `id` - an alphanumeric string (plus `_`) used to identify the schema.

If no id is set, the schema id defaults to the object key it is associated with. If the schema is
used in an array or alternatives type and no id is set, the schema is unreachable.

#### `any.invalid(...values)` - aliases: `disallow`, `not`

Disallows values where:
- `values` - the forbidden values which can be of any type and will be matched against the validated value before applying any other rules. Supports [references](#refkey-options) and [in-references](#inref-options). If the first value is [`Joi.override`](#override), will override any previously set values.

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

Possible validation errors: [`any.invalid`](#anyinvalid)

#### `any.isAsync()`

Returns a boolean indicating whether this schema contains a rule that requires asynchronous validation.

#### `any.keep()`

Same as [`rule({ keep: true })`](#anyruleoptions).

Note that `keep()` will terminate the current ruleset and cannot be followed by another
rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.

#### `any.label(name)`

Overrides the key name in error messages.
- `name` - the name of the key.

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

#### `any.message(message)`

Same as [`rule({ message })`](#anyruleoptions).

Note that `message()` will terminate the current ruleset and cannot be followed by another
rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.

#### `any.messages(messages)`

Same as [`any.prefs({ messages })`](#anyprefsoptions---aliases-preferences-options).

Note that while [`any.message()`](#anymessagemessage) applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.

#### `any.meta(meta)`

Attaches metadata to the key where:
- `meta` - the meta object to attach.

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

#### `any.note(...notes)`

Annotates the key where:
- `notes` - the note string or multiple notes as individual arguments.

```js
const schema = Joi.any().note('this is special', 'this is important');
```

#### `any.only()`

Requires the validated value to match of the provided `any.allow()` values. It has no effect when
called together with `any.valid()` since it already sets the requirements. When used with
`any.allow()` it converts it to an `any.valid()`.

#### `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.

Note: this does not allow a `null` value. To do that, use [`any.allow(value)`](#anyallowvalue). Or both!

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

#### `any.prefs(options)` - aliases: `preferences`, `options`

Overrides the global `validate()` options for the current key and any sub-key where:
- `options` - an object with the same optional keys as [`any.validate()`](#anyvalidatevalue-options).

```js
const schema = Joi.any().prefs({ convert: false });
```

#### `any.presence(mode)`

Sets the presence mode for the schema where:
- `mode` - can be one of `'optional'`, `'required'`, or `'forbidden'`

Same as calling `any.optional()`, `any.required()`, or `any.forbidden()`.

#### `any.raw([enabled])`

Outputs the original untouched value instead of the casted value where:
- `enabled` - if `true`, the original result is returned, otherwise the validated value. Defaults to `true`.

Note that the raw value is only applied after validation and any references to the value use the
validated value, not the raw value.

```js
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' }
```

#### `any.required()` - aliases: `exist`

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

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

Possible validation errors: [`any.required`](#anyrequired)

#### `any.result(mode)`

Set the result mode where:
- `mode` - one of `'raw'` (same as `any.raw()`) or `'strip'` (same as `any.strip()`).

#### `any.rule(options)`

Applies a set of rule options to the current ruleset or last rule added where:
- `options` - the rules to apply where:
  - `keep` - if `true`, the rules will not be replaced by the same unique rule later. For example, `Joi.number().min(1).rule({ keep: true }).min(2)` will keep both `min()` rules instead of the later rule overriding the first. Defaults to `false`.
  - `message` - a single message string or a messages object where each key is an error code and corresponding message string as value. The object is the same as the `messages` used as an option in [`any.validate()`](#anyvalidatevalue-options). The strings can be plain messages or a message template.
  - `warn` - if `true`, turns any error generated by the ruleset to warnings.

When applying rule options, the last rule (e.g. `min()`) is used unless there is an active ruleset defined (e.g. `$.min().max()`) in which case the options are applied to all the provided rules. Once `rule()` is called, the previous rules can no longer be modified and any active ruleset is terminated.

Rule modifications can only be applied to supported rules. Most of the `any` methods do not support rule modifications because they are implemented using schema flags (e.g. `required()`) or special internal implementation (e.g. `valid()`). In those cases, use the `any.messages()` method to override the error codes for the errors you want to customize.

#### `any.ruleset` - aliases: `$`

Starts a ruleset in order to apply multiple [rule options](#anyruleoptions). The set ends when
[`rule()`](#anyruleoptions), [`keep()`](#anykeep), [`message()`](#anymessagemessage), or [`warn()`](#anywarn) is called.

```js
const schema = Joi.number().ruleset.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });
```

```js
const schema = Joi.number().$.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });
```

#### `any.shared(schema)`

Registers a schema to be used by descendants of the current schema in named link references, where:
- `schema` - a **joi** schema with an id.

```js
  const schema = Joi.object({
      a: [Joi.string(), Joi.link('#x')],
      b: Joi.link('#type.a')
  })
      .shared(Joi.number().id('x'))
      .id('type');
```

#### `any.strict(isStrict)`

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.

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

#### `any.strip([enabled])`

Marks a key to be removed from a resulting object or array after validation to sanitize the output
where:
- `enabled` - if `true`, the value is stripped, otherwise the validated value is retained. Defaults
  to `true`.

```js
const schema = Joi.object({
    username: Joi.string(),
    password: Joi.string().strip()
});

schema.validate({ username: 'test', password: 'hunter2' }); // result.value = { username: 'test' }

const schema = Joi.array().items(Joi.string(), Joi.any().strip());

schema.validate(['one', 'two', true, false, 1, 2]); // result.value = ['one', 'two']
```

#### `any.tag(...tags)`

Annotates the key where:
- `tags` - the tag string or multiple tags (each as an argument).

```js
const schema = Joi.any().tag('api', 'user');
```

#### `any.tailor(targets)`

Applies any assigned target alterations to a copy of the schema that were applied via
[`any.alter()`](#anyaltertargets) where:
- `targets` - a single target string or array or target strings to apply.

```js
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.unit(name)`

Annotates the key where:
- `name` - the unit name of the value.

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

#### `any.valid(...values)` - aliases: `equal`

Adds the provided values into the allowed values list and marks them as the only valid values allowed 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](#refkey-options) and [in-references](#inref-options). If the first value is [`Joi.override`](#override), will override any previously set values. If the only value is [`Joi.override`](#override), will also remove the `only` flag from the schema.

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

Possible validation errors: [`any.only`](#anyonly)

#### `any.validate(value, [options])`

Validates a value using the current schema and options where:
- `value` - the value being validated.
- `options` - an optional object with the following optional keys:
  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.
  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.
  - `cache` - when `true`, schema caching is enabled (for schemas with explicit caching rules). Default to `true`.
  - `context` - provides an external data set to be used in [references](#refkey-options). Can only be set as an external option to `validate()` and not using `any.prefs()`.
  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.
  - `dateFormat` - sets the string format used when converting dates to strings in error messages and casting. Options are:
    - `'date'` - date string.
    - `'iso'` - date time ISO string. This is the default.
    - `'string'` - JS default date time string.
    - `'time'` - time string.
    - `'utc'` - UTC date time string.
  - `debug` - when `true`, valid results and throw errors are decorated with a `debug` property which includes an array of the validation steps used to generate the returned result. Defaults to `false`.
  - `errors` - error formatting settings:
    - `escapeHtml` - when `true`, error message templates will escape special characters to HTML entities, for security purposes. Defaults to `false`.
    - `label` - defines the value used to set the `label` context variable:
      - `'path'` - the full path to the value being validated. This is the default value.
      - `'key'` - the key of the value being validated.
      - `false` - remove any label prefix from error message, including the `""`.
    - `language` - the preferred language code for error messages. The value is matched against keys at the root of the `messages` object, and then the error code as a child key of that. Can be a reference to the value, global context, or local context which is the root value passed to the validation function. Note that references to the value are usually not what you want as they move around the value structure relative to where the error happens. Instead, either use the global context, or the absolute value (e.g. `Joi.ref('/variable')`);
    - `render` - when `false`, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time. Defaults to `true`.
    - `stack` - when `true`, the main error will possess a stack trace, otherwise it will be disabled. Defaults to `false` for performance reasons. Has no effect on platforms other than V8/node.js as it uses the [Stack trace API](https://v8.dev/docs/stack-trace-api).
    - `wrap` - overrides the way values are wrapped (e.g. `[]` around arrays, `""` around labels and variables prefixed with `:`). Each key can be set to a string with one (same character before and after the value) or two characters (first character before and second character after), or `false` to disable wrapping:
        - `label` - the characters used around `{#label}` references. Defaults to `'"'`.
        - `array` - the characters used around array values. Defaults to `'[]'`.
        - `string` - the characters used around each array string values. Defaults to `false`.
    - `wrapArrays` - if `true`, array values in error messages are wrapped in `[]`. Defaults to `true`.
  - `externals` - if `false`, the external rules set with [`any.external()`](#anyexternalmethod-description) are ignored, which is required to ignore any external validations in synchronous mode (or an exception is thrown). Defaults to `true`.
  - `messages` - overrides individual error messages. Defaults to no override (`{}`). Use the `'*'` error code as a catch-all for all error codes that do not have a message provided in the override. Messages use the same rules as [templates](#template-syntax). Variables in double braces `{{var}}` are HTML escaped if the option `errors.escapeHtml` is set to `true`.
  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.
  - `nonEnumerables` - when `true`, inputs are shallow cloned to include non-enumerable properties. Defaults to `false`.
  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`. Defaults to `'optional'`.
  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.
  - `stripUnknown` - remove unknown elements from objects and arrays. Defaults to `false`.
    - when an `object` :
      - `arrays` - set to `true` to remove unknown items from arrays.
      - `objects` - set to `true` to remove unknown keys from objects.
    - when `true`, it is equivalent to having `{ arrays: false, objects: true }`.

Returns an object with the following keys:
- `value` - the validated and normalized value.
- `error` - the validation errors if found.
- `warning` - the generated warnings if any.
- `artifacts` - a `Map` containing any passing rules' artifacts and their corresponding array of paths.

```js
const schema = Joi.object({
    a: Joi.number()
});

const value = {
    a: '123'
};

const result = schema.validate(value);
// result -> { value: { "a" : 123 } }
```

#### `any.validateAsync(value, [options])`

Validates a value asynchronously using the current schema and options where:
- `value` - the value being validated.
- `options` - an optional object as described in [`any.validate()`](#anyvalidatevalue-options), with the following additional settings:
    - `artifacts` - when `true`, artifacts are returned alongside the value (i.e. `{ value, artifacts }`). Defaults to `false`.
    - `warnings` - when `true`, warnings are returned alongside the value (i.e. `{ value, warning }`). Defaults to `false`.

Returns a Promise that resolves into the validated value when the value is valid. If the value is valid and the `warnings` or `debug` options are set to `true`, returns an object `{ value, warning, debug }`. If validation fails, the promise rejects with the validation error.

```js
const schema = Joi.object({
    a: Joi.number()
});

const value = {
    a: '123'
};

try {
  const value = await schema.validateAsync(value);
  // value -> { "a" : 123 }
}
catch (err) {
}
```

#### `any.warn()`

Same as [`rule({ warn: true })`](#anyruleoptions).

Note that `warn()` will terminate the current ruleset and cannot be followed by another rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.

#### `any.warning(code, [context])`

Generates a warning where:
- `code` - the warning code. Can be an existing error code or a custom code. If a custom code is used, a matching error message definition must be configured via [`any.message()`](#anymessagemessage), [`any.prefs()`](#anyprefsoptions--aliases-preferences-options), or validation `messages` option.
- `context` - optional context object.

When calling [`any.validateAsync()`](#anyvalidateasyncvalue-options), set the `warning` option to `true` to enable warnings. Warnings are reported separately from errors alongside the result value via the `warning` key (i.e. `{ value, warning }`). Warning are always included when calling [`any.validate()`](#anyvalidatevalue-options).

```js
const schema = Joi.any()
    .warning('custom.x', { w: 'world' })
    .message({ 'custom.x': 'hello {#w}!' });

const { value, error, warning } = schema.validate('anything');

// value -> 'anything';
// error -> null
// warning -> { message: 'hello world!', details: [...] }

// or

try {
    const { value, warning } = await schema.validateAsync('anything', { warnings: true });
    // value -> 'anything';
    // warning -> { message: 'hello world!', details: [...] }
}
catch (err) { }
```

#### `any['~standard']`

Provides compatibility with the [Standard Schema](https://github.com/standard-schema/spec) specification. It contains a `jsonSchema` object with the following methods:

- `input([options])` - returns the JSON