{"owner":"hapijs","repo":"joi","hasSkills":true,"totalSkillsCount":1,"totalTokensCount":11985,"categories":["project-spec"],"hasMcp":false,"mcpConfig":null,"found":["API.md"],"skills":{"API.md":"\n### Introduction\n\n**joi** lets you describe your data using a simple, intuitive, and readable language.\n\n#### Example\n\n```js\nconst Joi = require('joi');\n\nconst schema = Joi.object({\n    username: Joi.string()\n        .alphanum()\n        .min(3)\n        .max(30)\n        .required(),\n\n    password: Joi.string()\n        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),\n\n    repeat_password: Joi.ref('password'),\n\n    access_token: [\n        Joi.string(),\n        Joi.number()\n    ],\n\n    birth_year: Joi.number()\n        .integer()\n        .min(1900)\n        .max(2013),\n\n    email: Joi.string()\n        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n})\n    .with('username', 'birth_year')\n    .xor('password', 'access_token')\n    .with('password', 'repeat_password');\n\n\nschema.validate({ username: 'abc', birth_year: 1994 });\n// -> { value: { username: 'abc', birth_year: 1994 } }\n\nschema.validate({});\n// -> { value: {}, error: '\"username\" is required' }\n\n// Also -\n\ntry {\n    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });\n}\ncatch (err) { }\n```\n\nThe above schema defines the following constraints:\n* `username`\n    * a required string\n    * must contain only alphanumeric characters\n    * at least 3 characters long but no more than 30\n    * must be accompanied by `birth_year`\n* `password`\n    * an optional string\n    * must satisfy the custom regex pattern\n    * cannot appear together with `access_token`\n    * must be accompanied by `repeat_password` and equal to it\n* `access_token`\n    * an optional, unconstrained string or number\n* `birth_year`\n    * an integer between 1900 and 2013\n* `email`\n    * a valid email address string\n    * must have two domain parts e.g. `example.com`\n    * TLD must be `.com` or `.net`\n\n### General Usage\n\nUsage is a two steps process:\n\nFirst, a schema is constructed using the provided types and constraints:\n\n```js\nconst schema = Joi.object({\n    a: Joi.string()\n});\n```\n\nNote that **joi** schema objects are immutable which means every additional rule added (e.g.\n`.min(5)`) will return a new schema object.\n\nSecond, the value is validated against the defined schema:\n\n```js\nconst { error, value } = schema.validate({ a: 'a string' });\n```\n\nIf the input is valid, then the `error` will be `undefined`. If the input is invalid, `error` is assigned\na [`ValidationError`](#validationerror) object\nproviding more information.\n\nThe schema can be a plain JavaScript object where every key is assigned a **joi** type, or it can be a **joi** type directly:\n\n```js\nconst schema = Joi.string().min(10);\n```\n\nIf the schema is a **joi** type, the `schema.validate(value)` can be called directly on the type. When passing a non-type schema object,\nthe module converts it internally to an object() type equivalent to:\n\n```js\nconst schema = Joi.object().keys({\n    a: Joi.string()\n});\n```\n\nWhen validating a schema:\n\n* Values (or keys in case of objects) are optional by default.\n\n    ```js\n    Joi.string().validate(undefined); // validates fine\n    ```\n\n    To disallow this behavior, you can either set the schema as `required()`, or set `presence` to `\"required\"` when passing `options`:\n\n    ```js\n    Joi.string().required().validate(undefined);\n    // or\n    Joi.string().validate(undefined, /* options */ { presence: \"required\" });\n    ```\n\n* Strings are utf-8 encoded by default.\n* Rules are defined in an additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.\n\n### `assert(value, schema, [message], [options])`\n\nValidates a value against a schema and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.assert('x', Joi.number());\n```\n\n### `attempt(value, schema, [message], [options])`\n\nValidates a value against a schema, returns valid object, and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.attempt('x', Joi.number()); // throws error\nconst result = Joi.attempt('4', Joi.number()); // result -> 4\n```\n\n### `cache.provision([options])`\n\nProvisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and\nbooleans) where:\n- `options` - optional settings:\n    - `max` - number of items to store in the cache before the least used items are dropped.\n      Defaults to `1000`.\n\n### `checkPreferences(prefs)`\n\nChecks if the provided preferences are valid where:\n- `prefs` - the preferences object to validate.\n\nThrows an exception if the `prefs` object is invalid.\n\nThe method is provided to perform inputs validation for the [`any.validate()`](#anyvalidatevalue-options)\nand [`any.validateAsync()`](#anyvalidateasyncvalue-options) methods. Validation is not performed\nautomatically for performance reasons. Instead, manually validate the preferences passed once and\nreuse.\n\n### `compile(schema, [options])`\n\nConverts literal schema definition to **joi** schema object (or returns the same back if already a\n**joi** schema object) where:\n- `schema` - the schema definition to compile.\n- `options` - optional settings:\n    - `legacy` - if `true` and the provided schema is (or contains parts) using an older version of\n      **joi**, will return a compiled schema that is compatible with the older version. If `false`,\n      the schema is always compiled using the current version and if older schema components are\n      found, an error is thrown.\n\n```js\nconst definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];\nconst schema = Joi.compile(definition);\n\n// Same as:\n\nconst schema = Joi.alternatives().try(\n    Joi.string().valid('key'),\n    Joi.number().valid(5),\n    Joi.object({\n        a: Joi.boolean().valid(true),\n        b: Joi.alternatives().try(\n            Joi.string().pattern(/^a/),\n            Joi.string().valid('boom')\n        )\n    })\n);\n```\n\n### `defaults(modifier)`\n\nCreates a new **joi** instance that applies the provided modifier function to every new schemas\nwhere:\n- `modifier` - a function with signature `function(schema)` that must return a schema object.\n\n```js\nconst custom = Joi.defaults((schema) => {\n\n    switch (schema.type) {\n        case 'string':\n            return schema.allow('');\n        case 'object':\n            return schema.min(1);\n        default:\n            return schema;\n    }\n});\n\nconst schema = custom.object();   // Returns Joi.object().min(1)\n```\n\n### `expression(template, [options])` - aliases: `x`\n\nGenerates a dynamic expression using a template string where:\n- `template` - the template string using the [template syntax](#template-syntax).\n- `options` - optional settings used when creating internal references. Supports the same options\n  as [`ref()`](#refkey-options), in addition to those options:\n  - `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.\n\n#### Template syntax\n\nThe 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`).\n\nIf 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.\n\nThe 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. `[.]`).\n\nThe 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).\n\nThe reference names can have one of the following prefixes:\n- `#` - 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.\n- `$` - 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).\n- any other variable references a key within the current value being validated.\n\nThe formula syntax also supports built-in functions:\n- `if(condition, then, otherwise)` - returns `then` when `condition` is truthy, otherwise `otherwise`.\n- `length(item)` - return the length of an array or string, the number of keys of an object, otherwise `null`.\n- `msg(code)` - embeds another error code message.\n- `number(value)` - cast value to a number.\n\nAnd the following constants:\n- `null`\n- `true`\n- `false`\n\n### `extend(...extensions)`\n\nCreates a new customized instance of the **joi** module where:\n- `extensions` - the extensions configurations as described in [Extensions](#extensions).\n\nNote that the original **joi** module is not modified by this.\n\n### `in(ref, [options])`\n\nCreates a [reference](#refkey-options) that when resolved, is used as an array of values to match against the rule, where:\n- `ref` - same as [`Joi.ref()`](#refkey-options).\n- `options` - same as [`Joi.ref()`](#refkey-options).\n\nCan only be used in rules that support in-references.\n\n```js\nconst schema = Joi.object({\n    a: Joi.array().items(Joi.number()),\n    b: Joi.number().valid(Joi.in('a'))\n});\n```\n\n### `isError(err)`\n\nChecks whether or not the provided argument is a validation error.\n\n```js\nJoi.isError(new Error()); // returns false\n```\n\n### `isExpression(expression)`\n\nChecks whether or not the provided argument is an expression.\n\n```js\nconst expression = Joi.x('{a}');\nJoi.isExpression(expression); // returns true\n```\n\n### `isRef(ref)`\n\nChecks whether or not the provided argument is a reference. Useful if you want to post-process error messages.\n\n```js\nconst ref = Joi.ref('a');\nJoi.isRef(ref); // returns true\n```\n\n### `isSchema(schema, [options])`\n\nChecks whether or not the provided argument is a **joi** schema where:\n- `schema` - the value being checked.\n- `options` - optional settings:\n    - `legacy` - if `true`, will identify schemas from older versions of joi, otherwise will throw an error. Defaults to `false`.\n\n```js\nconst schema = Joi.any();\nJoi.isSchema(schema); // returns true\n```\n\n### `override`\n\nA special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.\n\n```js\nJoi.valid(1).valid(Joi.override, 2);\n\n// Same as:\n\nJoi.valid(2);\n\n// Whereas:\n\nJoi.valid(1).valid(2);\n\n// Is the same as:\n\nJoi.valid(1, 2);\n```\n\n### `ref(key, [options])`\n\nGenerates 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.\n\nReferences support the following arguments:\n- `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).\n- `options` - optional settings:\n    - `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`.\n    - `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`.\n    - `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:\n      - `global` - references to the globally provided `context` preference. Defaults to `'$'`.\n      - `local` - references to error-specific or rule specific context. Defaults to `'#'`.\n      - `root` - references to the root value being validated. Defaults to `'/'`.\n    - `separator` - overrides the default `.` hierarchy separator. Set to `false` to treat the `key` as a literal value.\n    - `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).\n    - `in` - creates an [in-reference](#inref-options).\n    - `iterables` - when `true`, the reference resolves by reaching into maps and sets.\n    - `render` - when `true`, the value of the reference is used instead of its name in error messages and template rendering. Defaults to `false`.\n\nNote 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).\n\n```js\nconst schema = Joi.object({\n    a: Joi.ref('b.c'),\n    b: {\n        c: Joi.any()\n    },\n    c: Joi.ref('$x')\n});\n\nawait schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } });\n```\n\n#### Relative references\n\nBy default, a reference is relative to the parent of the current value (the reference key is lookup\nup inside the parent). This means that in the schema:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nThe reference `Joi.ref('c')` points to `c` which is a sibling of `d` - the reference starting point\nis `d`'s parent which is `b`. This schema means that `d` must be equal to `c`.\n\nIn order to reference a parent peer, you can use a separator prefix where (using `.` as separator):\n- `.` - self\n- `..` - parent (same as no prefix)\n- `...` - grandparent\n- `....` - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c'),\n            e: Joi.ref('...a'),\n            f: Joi.ref('....y')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nAnother way to specify the relative starting point is using the `ancestor` option where:\n- 0 - self\n- 1 - parent (this is the default value if no key prefix is present)\n- 2 - grandparent\n- 3 - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c', { ancestor: 1 }),\n            e: Joi.ref('a', { ancestor: 2 }),\n            f: Joi.ref('y', { ancestor: 3 })\n        }\n    },\n    y: Joi.any()\n}\n```\n\nNote that if a reference tries to reach beyond the value root, validation fails.\n\nTo specify an absolute path from the value root, use the `/` prefix:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.ref('/x.a')\n        }\n    }\n}\n```\n\n### `version`\n\nProperty showing the current version of **joi** being used.\n\n### `types()`\n\nReturns an object where each key is a plain joi schema type. Useful for creating type shortcuts\nusing deconstruction. Note that the types are already formed and do not need to be called as\nfunctions (e.g. `string`, not `string()`).\n\n```js\nconst Joi = require('joi');\nconst { object, string } = Joi.types();\n\nconst schema = object.keys({\n  property: string.min(4)\n});\n```\n\n### `any`\n\nGenerates a schema object that matches any data type.\n\n```js\nconst any = Joi.any();\nawait any.validateAsync('a');\n```\n\n#### `any.type`\n\nGets the type of the schema.\n\n```js\nconst schema = Joi.string();\n\nschema.type === 'string';   // === true\n```\n\n#### `any.allow(...values)`\n\nAllows values where:\n- `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.\n\nNote that this list of allowed values is in *addition* to any other permitted values.\nTo create an exclusive list of values, see [`any.valid(value)`](#anyvalidvalues---aliases-equal).\n\n```js\nconst schema = {\n    a: Joi.any().allow('a'),\n    b: Joi.any().allow('b', 'B')\n};\n```\n\n#### `any.alter(targets)`\n\nAssign target alteration options to a schema that are applied when [`any.tailor()`](#anytailortargets)\nis called where:\n- `targets` - an object where each key is a target name, and each value is a function with signature\n  `function(schema)` that returns a schema.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor('post');\n```\n\n#### `any.artifact(id)`\n\nAssigns the schema an artifact id which is included in the validation result if the rule passed validation where:\n- `id` - any value other than `undefined` which will be returned as-is in the result `artifacts` map.\n\n```js\nconst schema = {\n    a: [\n        Joi.number().max(10).artifact('under'),\n        Joi.number().min(11).artifact('over')\n    ]\n};\n```\n\n#### `any.cache([cache])`\n\nAdds caching to the schema which will attempt to cache the validation results (success and\nfailures) of incoming inputs where:\n- `cache` - an optional cache implementation compatible with the built-in cache provided by\n  [`cache.provision()`](#cacheprovisionoptions). If no `cache` is passed, a default cache\n  is provisioned by using [`cache.provision()`](#cacheprovisionoptions) internally.\n\nNote that deciding which inputs to cache is left to the cache implementation. The built-in\ncache will only store simple values such as `undefined`, `null`, strings, numbers, and booleans.\nAny changes to the schema after `any.cache()` is called will disable caching on the resulting\nschema. this means that if `.cache()` is not the last statement in a schema definition, caching\nwill be disabled.\n\nTo disable caching for an entire schema in runtime, pass the `cache` preference set to `false`.\n\nCaching ignores changes to runtime preference. This means that if you run `schema.validate()`\nonces using one set of preferences, and then again using another set (for example, changing the\nlanguage), the cached results will be based on the first set of preferences.\n\nBefore using caching, it is recommended to consider the performance gain as it will not speed up\nevery schema. Schemas using `.valid()` list will not benefit from caching.\n\nCaching will be ignored when the schema uses references outside of the value scope.\n\n##### Cache interface\n\nCustom cache implementation must implement the following interface:\n\n```js\nclass {\n    set(key, value) {}\n    get(key) { return found ? value : undefined; }\n}\n```\n\nNote 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.\n\n#### `any.cast(to)`\n\nCasts the validated value to the specified type where:\n- `to` - the value target type. Each **joi** schema type supports its own set of cast targets:\n    - `'map'` - supported by the `Joi.object()` type, converts the result to a `Map` object containing the object key-value pairs.\n    - `'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`.\n    - `'set'` - supported by the `Joi.array()` type, converts the result to a `Set` object containing the array values.\n    - `'string'` - supported by `Joi.binary()`, `Joi.boolean()`, `Joi.date()`, and `Joi.number()`, converts the result to a string.\n\n#### `any.concat(schema)`\n\nReturns a new type that is the result of adding the rules of one type to another where:\n- `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.\n\n```js\nconst a = Joi.string().valid('a');\nconst b = Joi.string().valid('b');\nconst ab = a.concat(b);\n```\n\n#### `any.custom(method, [description])`\n\nAdds a custom validation function to execute arbitrary code where:\n- `method` - the custom (synchronous only) validation function using signature `function(value, helpers)` where:\n    - `value` - the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local], [localState])` - a method to generate error codes using a message code, optional local context and optional validation local state.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n\nNote: if the method fails to return a value, the value will be unset or returned as `undefined`.\n\n```js\nconst method = (value, helpers) => {\n\n    // Throw an error (will be replaced with 'any.custom' error)\n    if (value === '1') {\n        throw new Error('nope');\n    }\n\n    // Replace value with a new value\n    if (value === '2') {\n        return '3';\n    }\n\n    // Use error to return an existing error code\n    if (value === '4') {\n        return helpers.error('any.invalid');\n    }\n\n    // Override value with undefined to unset\n    if (value === '5') {\n        return undefined;\n    }\n\n    // Return the value unchanged\n    return value;\n};\n\nconst schema = Joi.string().custom(method, 'custom validation');\n```\n\nPossible validation errors: [`any.custom`](#anycustom)\n\n#### `any.default([value])`\n\nSets a default value if the original value is `undefined` where:\n- `value` - the default value. One of:\n    - a literal value (string, number, object, etc.).\n    - a [references](#refkey-options).\n    - a function which returns the default value using the signature `function(parent, helpers)` where:\n        - `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.\n        - `helpers` - same as those described in [`any.custom()`](#anycustommethod_description).\n\nWhen 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.\n\nNote 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).\n\n```js\nconst generateUsername = (parent, helpers) => {\n\n  return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase();\n};\n\ngenerateUsername.description = 'generated username';\n\nconst schema = Joi.object({\n    username: Joi.string().default(generateUsername),\n    firstname: Joi.string(),\n    lastname: Joi.string(),\n    created: Joi.date().default(Date.now),\n    status: Joi.string().default('registered')\n});\n\nconst { value } = schema.validate({\n    firstname: 'Jane',\n    lastname: 'Doe'\n});\n\n// value.status === 'registered'\n// value.username === 'jane-doe'\n// value.created will be the time of validation\n```\n\nPossible validation errors: [`any.default`](#anydefault)\n\n#### `any.describe()`\n\nReturns an object that represents the internal configuration of the schema. Useful for debugging\nand exposing a schema's configuration to other systems, like valid values in a user interface.\n\n```js\nconst schema = Joi.any().valid('foo', 'bar');\nconsole.log(schema.describe());\n```\n\nResults in:\n\n```\n{ type: 'any',\n  flags: { only: true },\n  valids: [ 'foo', 'bar' ] }\n```\n\n#### `any.description(desc)`\n\nAnnotates the key where:\n- `desc` - the description string.\n\n```js\nconst schema = Joi.any().description('this key will match anything you give it');\n```\n\n#### `any.empty(schema)`\n\nConsiders anything that matches the schema to be empty (`undefined`). Overrides any previous calls to empty.\n- `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.\n\n```js\nlet schema = Joi.string().empty('');\nschema.validate(''); // returns { error: null, value: undefined }\nschema = schema.empty();\nschema.validate(''); // returns { error: \"value\" is not allowed to be empty, value: '' }\n```\n\n#### `any.error(err)`\n\nOverrides the default **joi** error with a custom error if the rule fails where:\n- `err` can be:\n  - an instance of `Error` - the override error.\n  - 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.\n\nDo 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.\n\nNote 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.\n\n```js\nconst schema = Joi.string().error(new Error('Was REALLY expecting a string'));\nschema.validate(3);     // returns Error('Was REALLY expecting a string')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => new Error('\"foo\" requires a positive number'))\n});\nschema.validate({ foo: -2 });    // returns new Error('\"foo\" requires a positive number')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => {\n\n        return new Error('found errors with ' + errors.map((err) => `${err.local.key}(${err.local.limit}) with value ${err.local.value}`).join(' and '));\n    })\n});\nschema.validate({ foo: -2 });    // returns new Error('found errors with foo(0) with value -2')\n```\n\n#### `any.example(example, [options])`\n\nAdds examples to the schema where:\n- `example` - adds an example. Note that no validation is performed on the value.\n- `options` - optional settings:\n    - `override` - if `true`, replaces any existing examples. Defaults to `false`.\n\n```js\nconst schema = Joi.string().min(4).example('abcd');\n```\n\n#### `any.external(method, [description])`\n\nAdds an external validation rule where:\n- `method` - an async or sync function with signature `function(value, helpers)` which can either\n  return a replacement value, `undefined` to indicate no change, or throw an error, where:\n    - `value` - a clone of the object containing the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `linked` - if the schema is a link, the schema it links to.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local])` - a method to generate error codes using a message code and optional local context.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n- `description` - optional string used to document the purpose of the method.\n\nNote that external validation rules are only called after the all other validation rules for the\nentire schema (from the value root) are checked. This means that any changes made to the value by\nthe external rules are not available to any other validation rules during the non-external\nvalidation phase.\n\nIf schema validation failed, no external validation rules are called.\n\n#### `any.extract(path)`\n\nReturns a sub-schema based on a path of object keys or schema ids where:\n- `path` - a dot `.` separated path string or a pre-split array of path keys. The keys must match\n  the sub-schema id or object key (if no id was explicitly set).\n\n```js\nconst schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });\nconst number = schema.extract('foo.bar');\n\n//or\nconst result = schema.extract(['foo', 'bar']); //same as number\n```\n\n#### `any.failover(value)`\n\nSets a failover value if the original value fails passing validation where:\n- `value` - the failover value. `value` supports [references](#refkey-options). `value` may be\n  assigned a function which returns the default value. If `value` is specified as a function\n  that accepts a single parameter, that parameter will be a context object that can be used to\n  derive the resulting value.\n\nNote that if `value` is an object, any changes to the object after `failover()` is called will change\nthe reference and any future assignment. Use a function when setting a dynamic value (e.g. the\ncurrent time).\n\nUsing a function with a single argument performs some internal cloning which has a performance\nimpact. If you do not need access to the context, define the function without any arguments.\n\nPossible validation errors: [`any.failover`](#anyfailover)\n\n#### `any.forbidden()`\n\nMarks a key as forbidden which will not allow any value except `undefined`. Used to explicitly forbid keys.\n\n```js\nconst schema = {\n    a: Joi.any().forbidden()\n};\n```\n\nPossible validation errors: [`any.unknown`](#anyunknown)\n\n#### `any.fork(paths, adjuster)`\n\nReturns a new schema where each of the path keys listed have been modified where:\n- `paths` - an array of key strings, a single key string, or an array of arrays of pre-split\n  key strings. Key string paths use dot `.` to indicate key hierarchy.\n- `adjuster` - a function using the signature `function(schema)` which must return a modified\n  schema. For example, `(schema) => schema.required()`.\n\nThe method does not modify the original schema.\n\n#### `any.id(id)`\n\nSets a schema id for reaching into the schema via [`any.extract()`](#anyextractpath) where:\n- `id` - an alphanumeric string (plus `_`) used to identify the schema.\n\nIf no id is set, the schema id defaults to the object key it is associated with. If the schema is\nused in an array or alternatives type and no id is set, the schema is unreachable.\n\n#### `any.invalid(...values)` - aliases: `disallow`, `not`\n\nDisallows values where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().invalid('a'),\n    b: Joi.any().invalid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.invalid`](#anyinvalid)\n\n#### `any.isAsync()`\n\nReturns a boolean indicating whether this schema contains a rule that requires asynchronous validation.\n\n#### `any.keep()`\n\nSame as [`rule({ keep: true })`](#anyruleoptions).\n\nNote that `keep()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.label(name)`\n\nOverrides the key name in error messages.\n- `name` - the name of the key.\n\n```js\nconst schema = {\n    first_name: Joi.string().label('First Name')\n};\n```\n\n#### `any.message(message)`\n\nSame as [`rule({ message })`](#anyruleoptions).\n\nNote that `message()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.messages(messages)`\n\nSame as [`any.prefs({ messages })`](#anyprefsoptions---aliases-preferences-options).\n\nNote that while [`any.message()`](#anymessagemessage) applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.\n\n#### `any.meta(meta)`\n\nAttaches metadata to the key where:\n- `meta` - the meta object to attach.\n\n```js\nconst schema = Joi.any().meta({ index: true });\n```\n\n#### `any.note(...notes)`\n\nAnnotates the key where:\n- `notes` - the note string or multiple notes as individual arguments.\n\n```js\nconst schema = Joi.any().note('this is special', 'this is important');\n```\n\n#### `any.only()`\n\nRequires the validated value to match of the provided `any.allow()` values. It has no effect when\ncalled together with `any.valid()` since it already sets the requirements. When used with\n`any.allow()` it converts it to an `any.valid()`.\n\n#### `any.optional()`\n\nMarks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default.\n\nNote: this does not allow a `null` value. To do that, use [`any.allow(value)`](#anyallowvalue). Or both!\n\n```js\nconst schema = Joi.any().optional();\n```\n\n#### `any.prefs(options)` - aliases: `preferences`, `options`\n\nOverrides the global `validate()` options for the current key and any sub-key where:\n- `options` - an object with the same optional keys as [`any.validate()`](#anyvalidatevalue-options).\n\n```js\nconst schema = Joi.any().prefs({ convert: false });\n```\n\n#### `any.presence(mode)`\n\nSets the presence mode for the schema where:\n- `mode` - can be one of `'optional'`, `'required'`, or `'forbidden'`\n\nSame as calling `any.optional()`, `any.required()`, or `any.forbidden()`.\n\n#### `any.raw([enabled])`\n\nOutputs the original untouched value instead of the casted value where:\n- `enabled` - if `true`, the original result is returned, otherwise the validated value. Defaults to `true`.\n\nNote that the raw value is only applied after validation and any references to the value use the\nvalidated value, not the raw value.\n\n```js\nconst timestampSchema = Joi.date().timestamp();\ntimestampSchema.validate('12376834097810'); // { error: null, value: Sat Mar 17 2362 04:28:17 GMT-0500 (CDT) }\n\nconst rawTimestampSchema = Joi.date().timestamp().raw();\nrawTimestampSchema.validate('12376834097810'); // { error: null, value: '12376834097810' }\n```\n\n#### `any.required()` - aliases: `exist`\n\nMarks a key as required which will not allow `undefined` as value. All keys are optional by default.\n\n```js\nconst schema = Joi.any().required();\n```\n\nPossible validation errors: [`any.required`](#anyrequired)\n\n#### `any.result(mode)`\n\nSet the result mode where:\n- `mode` - one of `'raw'` (same as `any.raw()`) or `'strip'` (same as `any.strip()`).\n\n#### `any.rule(options)`\n\nApplies a set of rule options to the current ruleset or last rule added where:\n- `options` - the rules to apply where:\n  - `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`.\n  - `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.\n  - `warn` - if `true`, turns any error generated by the ruleset to warnings.\n\nWhen 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.\n\nRule 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.\n\n#### `any.ruleset` - aliases: `$`\n\nStarts a ruleset in order to apply multiple [rule options](#anyruleoptions). The set ends when\n[`rule()`](#anyruleoptions), [`keep()`](#anykeep), [`message()`](#anymessagemessage), or [`warn()`](#anywarn) is called.\n\n```js\nconst schema = Joi.number().ruleset.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n```js\nconst schema = Joi.number().$.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n#### `any.shared(schema)`\n\nRegisters a schema to be used by descendants of the current schema in named link references, where:\n- `schema` - a **joi** schema with an id.\n\n```js\n  const schema = Joi.object({\n      a: [Joi.string(), Joi.link('#x')],\n      b: Joi.link('#type.a')\n  })\n      .shared(Joi.number().id('x'))\n      .id('type');\n```\n\n#### `any.strict(isStrict)`\n\nStrict mode sets the `options.convert` options to `false` which prevent type casting for the current key and any child keys.\n- `isStrict` - whether strict mode is enabled or not. Defaults to true.\n\n```js\nconst schema = Joi.any().strict();\n```\n\n#### `any.strip([enabled])`\n\nMarks a key to be removed from a resulting object or array after validation to sanitize the output\nwhere:\n- `enabled` - if `true`, the value is stripped, otherwise the validated value is retained. Defaults\n  to `true`.\n\n```js\nconst schema = Joi.object({\n    username: Joi.string(),\n    password: Joi.string().strip()\n});\n\nschema.validate({ username: 'test', password: 'hunter2' }); // result.value = { username: 'test' }\n\nconst schema = Joi.array().items(Joi.string(), Joi.any().strip());\n\nschema.validate(['one', 'two', true, false, 1, 2]); // result.value = ['one', 'two']\n```\n\n#### `any.tag(...tags)`\n\nAnnotates the key where:\n- `tags` - the tag string or multiple tags (each as an argument).\n\n```js\nconst schema = Joi.any().tag('api', 'user');\n```\n\n#### `any.tailor(targets)`\n\nApplies any assigned target alterations to a copy of the schema that were applied via\n[`any.alter()`](#anyaltertargets) where:\n- `targets` - a single target string or array or target strings to apply.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor(['post']);\n```\n\n#### `any.unit(name)`\n\nAnnotates the key where:\n- `name` - the unit name of the value.\n\n```js\nconst schema = Joi.number().unit('milliseconds');\n```\n\n#### `any.valid(...values)` - aliases: `equal`\n\nAdds the provided values into the allowed values list and marks them as the only valid values allowed where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().valid('a'),\n    b: Joi.any().valid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.only`](#anyonly)\n\n#### `any.validate(value, [options])`\n\nValidates a value using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object with the following optional keys:\n  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.\n  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.\n  - `cache` - when `true`, schema caching is enabled (for schemas with explicit caching rules). Default to `true`.\n  - `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()`.\n  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.\n  - `dateFormat` - sets the string format used when converting dates to strings in error messages and casting. Options are:\n    - `'date'` - date string.\n    - `'iso'` - date time ISO string. This is the default.\n    - `'string'` - JS default date time string.\n    - `'time'` - time string.\n    - `'utc'` - UTC date time string.\n  - `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`.\n  - `errors` - error formatting settings:\n    - `escapeHtml` - when `true`, error message templates will escape special characters to HTML entities, for security purposes. Defaults to `false`.\n    - `label` - defines the value used to set the `label` context variable:\n      - `'path'` - the full path to the value being validated. This is the default value.\n      - `'key'` - the key of the value being validated.\n      - `false` - remove any label prefix from error message, including the `\"\"`.\n    - `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')`);\n    - `render` - when `false`, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time. Defaults to `true`.\n    - `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).\n    - `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:\n        - `label` - the characters used around `{#label}` references. Defaults to `'\"'`.\n        - `array` - the characters used around array values. Defaults to `'[]'`.\n        - `string` - the characters used around each array string values. Defaults to `false`.\n    - `wrapArrays` - if `true`, array values in error messages are wrapped in `[]`. Defaults to `true`.\n  - `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`.\n  - `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`.\n  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.\n  - `nonEnumerables` - when `true`, inputs are shallow cloned to include non-enumerable properties. Defaults to `false`.\n  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`. Defaults to `'optional'`.\n  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.\n  - `stripUnknown` - remove unknown elements from objects and arrays. Defaults to `false`.\n    - when an `object` :\n      - `arrays` - set to `true` to remove unknown items from arrays.\n      - `objects` - set to `true` to remove unknown keys from objects.\n    - when `true`, it is equivalent to having `{ arrays: false, objects: true }`.\n\nReturns an object with the following keys:\n- `value` - the validated and normalized value.\n- `error` - the validation errors if found.\n- `warning` - the generated warnings if any.\n- `artifacts` - a `Map` containing any passing rules' artifacts and their corresponding array of paths.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\nconst result = schema.validate(value);\n// result -> { value: { \"a\" : 123 } }\n```\n\n#### `any.validateAsync(value, [options])`\n\nValidates a value asynchronously using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object as described in [`any.validate()`](#anyvalidatevalue-options), with the following additional settings:\n    - `artifacts` - when `true`, artifacts are returned alongside the value (i.e. `{ value, artifacts }`). Defaults to `false`.\n    - `warnings` - when `true`, warnings are returned alongside the value (i.e. `{ value, warning }`). Defaults to `false`.\n\nReturns 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.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\ntry {\n  const value = await schema.validateAsync(value);\n  // value -> { \"a\" : 123 }\n}\ncatch (err) {\n}\n```\n\n#### `any.warn()`\n\nSame as [`rule({ warn: true })`](#anyruleoptions).\n\nNote that `warn()` will terminate the current ruleset and cannot be followed by another rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.warning(code, [context])`\n\nGenerates a warning where:\n- `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.\n- `context` - optional context object.\n\nWhen 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).\n\n```js\nconst schema = Joi.any()\n    .warning('custom.x', { w: 'world' })\n    .message({ 'custom.x': 'hello {#w}!' });\n\nconst { value, error, warning } = schema.validate('anything');\n\n// value -> 'anything';\n// error -> null\n// warning -> { message: 'hello world!', details: [...] }\n\n// or\n\ntry {\n    const { value, warning } = await schema.validateAsync('anything', { warnings: true });\n    // value -> 'anything';\n    // warning -> { message: 'hello world!', details: [...] }\n}\ncatch (err) { }\n```\n\n#### `any['~standard']`\n\nProvides compatibility with the [Standard Schema](https://github.com/standard-schema/spec) specification. It contains a `jsonSchema` object with the following methods:\n\n- `input([options])` - returns the JSON "},"files":{"API.md":"\n### Introduction\n\n**joi** lets you describe your data using a simple, intuitive, and readable language.\n\n#### Example\n\n```js\nconst Joi = require('joi');\n\nconst schema = Joi.object({\n    username: Joi.string()\n        .alphanum()\n        .min(3)\n        .max(30)\n        .required(),\n\n    password: Joi.string()\n        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),\n\n    repeat_password: Joi.ref('password'),\n\n    access_token: [\n        Joi.string(),\n        Joi.number()\n    ],\n\n    birth_year: Joi.number()\n        .integer()\n        .min(1900)\n        .max(2013),\n\n    email: Joi.string()\n        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n})\n    .with('username', 'birth_year')\n    .xor('password', 'access_token')\n    .with('password', 'repeat_password');\n\n\nschema.validate({ username: 'abc', birth_year: 1994 });\n// -> { value: { username: 'abc', birth_year: 1994 } }\n\nschema.validate({});\n// -> { value: {}, error: '\"username\" is required' }\n\n// Also -\n\ntry {\n    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });\n}\ncatch (err) { }\n```\n\nThe above schema defines the following constraints:\n* `username`\n    * a required string\n    * must contain only alphanumeric characters\n    * at least 3 characters long but no more than 30\n    * must be accompanied by `birth_year`\n* `password`\n    * an optional string\n    * must satisfy the custom regex pattern\n    * cannot appear together with `access_token`\n    * must be accompanied by `repeat_password` and equal to it\n* `access_token`\n    * an optional, unconstrained string or number\n* `birth_year`\n    * an integer between 1900 and 2013\n* `email`\n    * a valid email address string\n    * must have two domain parts e.g. `example.com`\n    * TLD must be `.com` or `.net`\n\n### General Usage\n\nUsage is a two steps process:\n\nFirst, a schema is constructed using the provided types and constraints:\n\n```js\nconst schema = Joi.object({\n    a: Joi.string()\n});\n```\n\nNote that **joi** schema objects are immutable which means every additional rule added (e.g.\n`.min(5)`) will return a new schema object.\n\nSecond, the value is validated against the defined schema:\n\n```js\nconst { error, value } = schema.validate({ a: 'a string' });\n```\n\nIf the input is valid, then the `error` will be `undefined`. If the input is invalid, `error` is assigned\na [`ValidationError`](#validationerror) object\nproviding more information.\n\nThe schema can be a plain JavaScript object where every key is assigned a **joi** type, or it can be a **joi** type directly:\n\n```js\nconst schema = Joi.string().min(10);\n```\n\nIf the schema is a **joi** type, the `schema.validate(value)` can be called directly on the type. When passing a non-type schema object,\nthe module converts it internally to an object() type equivalent to:\n\n```js\nconst schema = Joi.object().keys({\n    a: Joi.string()\n});\n```\n\nWhen validating a schema:\n\n* Values (or keys in case of objects) are optional by default.\n\n    ```js\n    Joi.string().validate(undefined); // validates fine\n    ```\n\n    To disallow this behavior, you can either set the schema as `required()`, or set `presence` to `\"required\"` when passing `options`:\n\n    ```js\n    Joi.string().required().validate(undefined);\n    // or\n    Joi.string().validate(undefined, /* options */ { presence: \"required\" });\n    ```\n\n* Strings are utf-8 encoded by default.\n* Rules are defined in an additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.\n\n### `assert(value, schema, [message], [options])`\n\nValidates a value against a schema and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.assert('x', Joi.number());\n```\n\n### `attempt(value, schema, [message], [options])`\n\nValidates a value against a schema, returns valid object, and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.attempt('x', Joi.number()); // throws error\nconst result = Joi.attempt('4', Joi.number()); // result -> 4\n```\n\n### `cache.provision([options])`\n\nProvisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and\nbooleans) where:\n- `options` - optional settings:\n    - `max` - number of items to store in the cache before the least used items are dropped.\n      Defaults to `1000`.\n\n### `checkPreferences(prefs)`\n\nChecks if the provided preferences are valid where:\n- `prefs` - the preferences object to validate.\n\nThrows an exception if the `prefs` object is invalid.\n\nThe method is provided to perform inputs validation for the [`any.validate()`](#anyvalidatevalue-options)\nand [`any.validateAsync()`](#anyvalidateasyncvalue-options) methods. Validation is not performed\nautomatically for performance reasons. Instead, manually validate the preferences passed once and\nreuse.\n\n### `compile(schema, [options])`\n\nConverts literal schema definition to **joi** schema object (or returns the same back if already a\n**joi** schema object) where:\n- `schema` - the schema definition to compile.\n- `options` - optional settings:\n    - `legacy` - if `true` and the provided schema is (or contains parts) using an older version of\n      **joi**, will return a compiled schema that is compatible with the older version. If `false`,\n      the schema is always compiled using the current version and if older schema components are\n      found, an error is thrown.\n\n```js\nconst definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];\nconst schema = Joi.compile(definition);\n\n// Same as:\n\nconst schema = Joi.alternatives().try(\n    Joi.string().valid('key'),\n    Joi.number().valid(5),\n    Joi.object({\n        a: Joi.boolean().valid(true),\n        b: Joi.alternatives().try(\n            Joi.string().pattern(/^a/),\n            Joi.string().valid('boom')\n        )\n    })\n);\n```\n\n### `defaults(modifier)`\n\nCreates a new **joi** instance that applies the provided modifier function to every new schemas\nwhere:\n- `modifier` - a function with signature `function(schema)` that must return a schema object.\n\n```js\nconst custom = Joi.defaults((schema) => {\n\n    switch (schema.type) {\n        case 'string':\n            return schema.allow('');\n        case 'object':\n            return schema.min(1);\n        default:\n            return schema;\n    }\n});\n\nconst schema = custom.object();   // Returns Joi.object().min(1)\n```\n\n### `expression(template, [options])` - aliases: `x`\n\nGenerates a dynamic expression using a template string where:\n- `template` - the template string using the [template syntax](#template-syntax).\n- `options` - optional settings used when creating internal references. Supports the same options\n  as [`ref()`](#refkey-options), in addition to those options:\n  - `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.\n\n#### Template syntax\n\nThe 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`).\n\nIf 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.\n\nThe 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. `[.]`).\n\nThe 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).\n\nThe reference names can have one of the following prefixes:\n- `#` - 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.\n- `$` - 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).\n- any other variable references a key within the current value being validated.\n\nThe formula syntax also supports built-in functions:\n- `if(condition, then, otherwise)` - returns `then` when `condition` is truthy, otherwise `otherwise`.\n- `length(item)` - return the length of an array or string, the number of keys of an object, otherwise `null`.\n- `msg(code)` - embeds another error code message.\n- `number(value)` - cast value to a number.\n\nAnd the following constants:\n- `null`\n- `true`\n- `false`\n\n### `extend(...extensions)`\n\nCreates a new customized instance of the **joi** module where:\n- `extensions` - the extensions configurations as described in [Extensions](#extensions).\n\nNote that the original **joi** module is not modified by this.\n\n### `in(ref, [options])`\n\nCreates a [reference](#refkey-options) that when resolved, is used as an array of values to match against the rule, where:\n- `ref` - same as [`Joi.ref()`](#refkey-options).\n- `options` - same as [`Joi.ref()`](#refkey-options).\n\nCan only be used in rules that support in-references.\n\n```js\nconst schema = Joi.object({\n    a: Joi.array().items(Joi.number()),\n    b: Joi.number().valid(Joi.in('a'))\n});\n```\n\n### `isError(err)`\n\nChecks whether or not the provided argument is a validation error.\n\n```js\nJoi.isError(new Error()); // returns false\n```\n\n### `isExpression(expression)`\n\nChecks whether or not the provided argument is an expression.\n\n```js\nconst expression = Joi.x('{a}');\nJoi.isExpression(expression); // returns true\n```\n\n### `isRef(ref)`\n\nChecks whether or not the provided argument is a reference. Useful if you want to post-process error messages.\n\n```js\nconst ref = Joi.ref('a');\nJoi.isRef(ref); // returns true\n```\n\n### `isSchema(schema, [options])`\n\nChecks whether or not the provided argument is a **joi** schema where:\n- `schema` - the value being checked.\n- `options` - optional settings:\n    - `legacy` - if `true`, will identify schemas from older versions of joi, otherwise will throw an error. Defaults to `false`.\n\n```js\nconst schema = Joi.any();\nJoi.isSchema(schema); // returns true\n```\n\n### `override`\n\nA special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.\n\n```js\nJoi.valid(1).valid(Joi.override, 2);\n\n// Same as:\n\nJoi.valid(2);\n\n// Whereas:\n\nJoi.valid(1).valid(2);\n\n// Is the same as:\n\nJoi.valid(1, 2);\n```\n\n### `ref(key, [options])`\n\nGenerates 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.\n\nReferences support the following arguments:\n- `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).\n- `options` - optional settings:\n    - `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`.\n    - `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`.\n    - `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:\n      - `global` - references to the globally provided `context` preference. Defaults to `'$'`.\n      - `local` - references to error-specific or rule specific context. Defaults to `'#'`.\n      - `root` - references to the root value being validated. Defaults to `'/'`.\n    - `separator` - overrides the default `.` hierarchy separator. Set to `false` to treat the `key` as a literal value.\n    - `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).\n    - `in` - creates an [in-reference](#inref-options).\n    - `iterables` - when `true`, the reference resolves by reaching into maps and sets.\n    - `render` - when `true`, the value of the reference is used instead of its name in error messages and template rendering. Defaults to `false`.\n\nNote 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).\n\n```js\nconst schema = Joi.object({\n    a: Joi.ref('b.c'),\n    b: {\n        c: Joi.any()\n    },\n    c: Joi.ref('$x')\n});\n\nawait schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } });\n```\n\n#### Relative references\n\nBy default, a reference is relative to the parent of the current value (the reference key is lookup\nup inside the parent). This means that in the schema:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nThe reference `Joi.ref('c')` points to `c` which is a sibling of `d` - the reference starting point\nis `d`'s parent which is `b`. This schema means that `d` must be equal to `c`.\n\nIn order to reference a parent peer, you can use a separator prefix where (using `.` as separator):\n- `.` - self\n- `..` - parent (same as no prefix)\n- `...` - grandparent\n- `....` - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c'),\n            e: Joi.ref('...a'),\n            f: Joi.ref('....y')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nAnother way to specify the relative starting point is using the `ancestor` option where:\n- 0 - self\n- 1 - parent (this is the default value if no key prefix is present)\n- 2 - grandparent\n- 3 - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c', { ancestor: 1 }),\n            e: Joi.ref('a', { ancestor: 2 }),\n            f: Joi.ref('y', { ancestor: 3 })\n        }\n    },\n    y: Joi.any()\n}\n```\n\nNote that if a reference tries to reach beyond the value root, validation fails.\n\nTo specify an absolute path from the value root, use the `/` prefix:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.ref('/x.a')\n        }\n    }\n}\n```\n\n### `version`\n\nProperty showing the current version of **joi** being used.\n\n### `types()`\n\nReturns an object where each key is a plain joi schema type. Useful for creating type shortcuts\nusing deconstruction. Note that the types are already formed and do not need to be called as\nfunctions (e.g. `string`, not `string()`).\n\n```js\nconst Joi = require('joi');\nconst { object, string } = Joi.types();\n\nconst schema = object.keys({\n  property: string.min(4)\n});\n```\n\n### `any`\n\nGenerates a schema object that matches any data type.\n\n```js\nconst any = Joi.any();\nawait any.validateAsync('a');\n```\n\n#### `any.type`\n\nGets the type of the schema.\n\n```js\nconst schema = Joi.string();\n\nschema.type === 'string';   // === true\n```\n\n#### `any.allow(...values)`\n\nAllows values where:\n- `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.\n\nNote that this list of allowed values is in *addition* to any other permitted values.\nTo create an exclusive list of values, see [`any.valid(value)`](#anyvalidvalues---aliases-equal).\n\n```js\nconst schema = {\n    a: Joi.any().allow('a'),\n    b: Joi.any().allow('b', 'B')\n};\n```\n\n#### `any.alter(targets)`\n\nAssign target alteration options to a schema that are applied when [`any.tailor()`](#anytailortargets)\nis called where:\n- `targets` - an object where each key is a target name, and each value is a function with signature\n  `function(schema)` that returns a schema.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor('post');\n```\n\n#### `any.artifact(id)`\n\nAssigns the schema an artifact id which is included in the validation result if the rule passed validation where:\n- `id` - any value other than `undefined` which will be returned as-is in the result `artifacts` map.\n\n```js\nconst schema = {\n    a: [\n        Joi.number().max(10).artifact('under'),\n        Joi.number().min(11).artifact('over')\n    ]\n};\n```\n\n#### `any.cache([cache])`\n\nAdds caching to the schema which will attempt to cache the validation results (success and\nfailures) of incoming inputs where:\n- `cache` - an optional cache implementation compatible with the built-in cache provided by\n  [`cache.provision()`](#cacheprovisionoptions). If no `cache` is passed, a default cache\n  is provisioned by using [`cache.provision()`](#cacheprovisionoptions) internally.\n\nNote that deciding which inputs to cache is left to the cache implementation. The built-in\ncache will only store simple values such as `undefined`, `null`, strings, numbers, and booleans.\nAny changes to the schema after `any.cache()` is called will disable caching on the resulting\nschema. this means that if `.cache()` is not the last statement in a schema definition, caching\nwill be disabled.\n\nTo disable caching for an entire schema in runtime, pass the `cache` preference set to `false`.\n\nCaching ignores changes to runtime preference. This means that if you run `schema.validate()`\nonces using one set of preferences, and then again using another set (for example, changing the\nlanguage), the cached results will be based on the first set of preferences.\n\nBefore using caching, it is recommended to consider the performance gain as it will not speed up\nevery schema. Schemas using `.valid()` list will not benefit from caching.\n\nCaching will be ignored when the schema uses references outside of the value scope.\n\n##### Cache interface\n\nCustom cache implementation must implement the following interface:\n\n```js\nclass {\n    set(key, value) {}\n    get(key) { return found ? value : undefined; }\n}\n```\n\nNote 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.\n\n#### `any.cast(to)`\n\nCasts the validated value to the specified type where:\n- `to` - the value target type. Each **joi** schema type supports its own set of cast targets:\n    - `'map'` - supported by the `Joi.object()` type, converts the result to a `Map` object containing the object key-value pairs.\n    - `'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`.\n    - `'set'` - supported by the `Joi.array()` type, converts the result to a `Set` object containing the array values.\n    - `'string'` - supported by `Joi.binary()`, `Joi.boolean()`, `Joi.date()`, and `Joi.number()`, converts the result to a string.\n\n#### `any.concat(schema)`\n\nReturns a new type that is the result of adding the rules of one type to another where:\n- `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.\n\n```js\nconst a = Joi.string().valid('a');\nconst b = Joi.string().valid('b');\nconst ab = a.concat(b);\n```\n\n#### `any.custom(method, [description])`\n\nAdds a custom validation function to execute arbitrary code where:\n- `method` - the custom (synchronous only) validation function using signature `function(value, helpers)` where:\n    - `value` - the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local], [localState])` - a method to generate error codes using a message code, optional local context and optional validation local state.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n\nNote: if the method fails to return a value, the value will be unset or returned as `undefined`.\n\n```js\nconst method = (value, helpers) => {\n\n    // Throw an error (will be replaced with 'any.custom' error)\n    if (value === '1') {\n        throw new Error('nope');\n    }\n\n    // Replace value with a new value\n    if (value === '2') {\n        return '3';\n    }\n\n    // Use error to return an existing error code\n    if (value === '4') {\n        return helpers.error('any.invalid');\n    }\n\n    // Override value with undefined to unset\n    if (value === '5') {\n        return undefined;\n    }\n\n    // Return the value unchanged\n    return value;\n};\n\nconst schema = Joi.string().custom(method, 'custom validation');\n```\n\nPossible validation errors: [`any.custom`](#anycustom)\n\n#### `any.default([value])`\n\nSets a default value if the original value is `undefined` where:\n- `value` - the default value. One of:\n    - a literal value (string, number, object, etc.).\n    - a [references](#refkey-options).\n    - a function which returns the default value using the signature `function(parent, helpers)` where:\n        - `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.\n        - `helpers` - same as those described in [`any.custom()`](#anycustommethod_description).\n\nWhen 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.\n\nNote 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).\n\n```js\nconst generateUsername = (parent, helpers) => {\n\n  return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase();\n};\n\ngenerateUsername.description = 'generated username';\n\nconst schema = Joi.object({\n    username: Joi.string().default(generateUsername),\n    firstname: Joi.string(),\n    lastname: Joi.string(),\n    created: Joi.date().default(Date.now),\n    status: Joi.string().default('registered')\n});\n\nconst { value } = schema.validate({\n    firstname: 'Jane',\n    lastname: 'Doe'\n});\n\n// value.status === 'registered'\n// value.username === 'jane-doe'\n// value.created will be the time of validation\n```\n\nPossible validation errors: [`any.default`](#anydefault)\n\n#### `any.describe()`\n\nReturns an object that represents the internal configuration of the schema. Useful for debugging\nand exposing a schema's configuration to other systems, like valid values in a user interface.\n\n```js\nconst schema = Joi.any().valid('foo', 'bar');\nconsole.log(schema.describe());\n```\n\nResults in:\n\n```\n{ type: 'any',\n  flags: { only: true },\n  valids: [ 'foo', 'bar' ] }\n```\n\n#### `any.description(desc)`\n\nAnnotates the key where:\n- `desc` - the description string.\n\n```js\nconst schema = Joi.any().description('this key will match anything you give it');\n```\n\n#### `any.empty(schema)`\n\nConsiders anything that matches the schema to be empty (`undefined`). Overrides any previous calls to empty.\n- `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.\n\n```js\nlet schema = Joi.string().empty('');\nschema.validate(''); // returns { error: null, value: undefined }\nschema = schema.empty();\nschema.validate(''); // returns { error: \"value\" is not allowed to be empty, value: '' }\n```\n\n#### `any.error(err)`\n\nOverrides the default **joi** error with a custom error if the rule fails where:\n- `err` can be:\n  - an instance of `Error` - the override error.\n  - 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.\n\nDo 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.\n\nNote 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.\n\n```js\nconst schema = Joi.string().error(new Error('Was REALLY expecting a string'));\nschema.validate(3);     // returns Error('Was REALLY expecting a string')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => new Error('\"foo\" requires a positive number'))\n});\nschema.validate({ foo: -2 });    // returns new Error('\"foo\" requires a positive number')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => {\n\n        return new Error('found errors with ' + errors.map((err) => `${err.local.key}(${err.local.limit}) with value ${err.local.value}`).join(' and '));\n    })\n});\nschema.validate({ foo: -2 });    // returns new Error('found errors with foo(0) with value -2')\n```\n\n#### `any.example(example, [options])`\n\nAdds examples to the schema where:\n- `example` - adds an example. Note that no validation is performed on the value.\n- `options` - optional settings:\n    - `override` - if `true`, replaces any existing examples. Defaults to `false`.\n\n```js\nconst schema = Joi.string().min(4).example('abcd');\n```\n\n#### `any.external(method, [description])`\n\nAdds an external validation rule where:\n- `method` - an async or sync function with signature `function(value, helpers)` which can either\n  return a replacement value, `undefined` to indicate no change, or throw an error, where:\n    - `value` - a clone of the object containing the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `linked` - if the schema is a link, the schema it links to.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local])` - a method to generate error codes using a message code and optional local context.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n- `description` - optional string used to document the purpose of the method.\n\nNote that external validation rules are only called after the all other validation rules for the\nentire schema (from the value root) are checked. This means that any changes made to the value by\nthe external rules are not available to any other validation rules during the non-external\nvalidation phase.\n\nIf schema validation failed, no external validation rules are called.\n\n#### `any.extract(path)`\n\nReturns a sub-schema based on a path of object keys or schema ids where:\n- `path` - a dot `.` separated path string or a pre-split array of path keys. The keys must match\n  the sub-schema id or object key (if no id was explicitly set).\n\n```js\nconst schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });\nconst number = schema.extract('foo.bar');\n\n//or\nconst result = schema.extract(['foo', 'bar']); //same as number\n```\n\n#### `any.failover(value)`\n\nSets a failover value if the original value fails passing validation where:\n- `value` - the failover value. `value` supports [references](#refkey-options). `value` may be\n  assigned a function which returns the default value. If `value` is specified as a function\n  that accepts a single parameter, that parameter will be a context object that can be used to\n  derive the resulting value.\n\nNote that if `value` is an object, any changes to the object after `failover()` is called will change\nthe reference and any future assignment. Use a function when setting a dynamic value (e.g. the\ncurrent time).\n\nUsing a function with a single argument performs some internal cloning which has a performance\nimpact. If you do not need access to the context, define the function without any arguments.\n\nPossible validation errors: [`any.failover`](#anyfailover)\n\n#### `any.forbidden()`\n\nMarks a key as forbidden which will not allow any value except `undefined`. Used to explicitly forbid keys.\n\n```js\nconst schema = {\n    a: Joi.any().forbidden()\n};\n```\n\nPossible validation errors: [`any.unknown`](#anyunknown)\n\n#### `any.fork(paths, adjuster)`\n\nReturns a new schema where each of the path keys listed have been modified where:\n- `paths` - an array of key strings, a single key string, or an array of arrays of pre-split\n  key strings. Key string paths use dot `.` to indicate key hierarchy.\n- `adjuster` - a function using the signature `function(schema)` which must return a modified\n  schema. For example, `(schema) => schema.required()`.\n\nThe method does not modify the original schema.\n\n#### `any.id(id)`\n\nSets a schema id for reaching into the schema via [`any.extract()`](#anyextractpath) where:\n- `id` - an alphanumeric string (plus `_`) used to identify the schema.\n\nIf no id is set, the schema id defaults to the object key it is associated with. If the schema is\nused in an array or alternatives type and no id is set, the schema is unreachable.\n\n#### `any.invalid(...values)` - aliases: `disallow`, `not`\n\nDisallows values where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().invalid('a'),\n    b: Joi.any().invalid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.invalid`](#anyinvalid)\n\n#### `any.isAsync()`\n\nReturns a boolean indicating whether this schema contains a rule that requires asynchronous validation.\n\n#### `any.keep()`\n\nSame as [`rule({ keep: true })`](#anyruleoptions).\n\nNote that `keep()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.label(name)`\n\nOverrides the key name in error messages.\n- `name` - the name of the key.\n\n```js\nconst schema = {\n    first_name: Joi.string().label('First Name')\n};\n```\n\n#### `any.message(message)`\n\nSame as [`rule({ message })`](#anyruleoptions).\n\nNote that `message()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.messages(messages)`\n\nSame as [`any.prefs({ messages })`](#anyprefsoptions---aliases-preferences-options).\n\nNote that while [`any.message()`](#anymessagemessage) applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.\n\n#### `any.meta(meta)`\n\nAttaches metadata to the key where:\n- `meta` - the meta object to attach.\n\n```js\nconst schema = Joi.any().meta({ index: true });\n```\n\n#### `any.note(...notes)`\n\nAnnotates the key where:\n- `notes` - the note string or multiple notes as individual arguments.\n\n```js\nconst schema = Joi.any().note('this is special', 'this is important');\n```\n\n#### `any.only()`\n\nRequires the validated value to match of the provided `any.allow()` values. It has no effect when\ncalled together with `any.valid()` since it already sets the requirements. When used with\n`any.allow()` it converts it to an `any.valid()`.\n\n#### `any.optional()`\n\nMarks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default.\n\nNote: this does not allow a `null` value. To do that, use [`any.allow(value)`](#anyallowvalue). Or both!\n\n```js\nconst schema = Joi.any().optional();\n```\n\n#### `any.prefs(options)` - aliases: `preferences`, `options`\n\nOverrides the global `validate()` options for the current key and any sub-key where:\n- `options` - an object with the same optional keys as [`any.validate()`](#anyvalidatevalue-options).\n\n```js\nconst schema = Joi.any().prefs({ convert: false });\n```\n\n#### `any.presence(mode)`\n\nSets the presence mode for the schema where:\n- `mode` - can be one of `'optional'`, `'required'`, or `'forbidden'`\n\nSame as calling `any.optional()`, `any.required()`, or `any.forbidden()`.\n\n#### `any.raw([enabled])`\n\nOutputs the original untouched value instead of the casted value where:\n- `enabled` - if `true`, the original result is returned, otherwise the validated value. Defaults to `true`.\n\nNote that the raw value is only applied after validation and any references to the value use the\nvalidated value, not the raw value.\n\n```js\nconst timestampSchema = Joi.date().timestamp();\ntimestampSchema.validate('12376834097810'); // { error: null, value: Sat Mar 17 2362 04:28:17 GMT-0500 (CDT) }\n\nconst rawTimestampSchema = Joi.date().timestamp().raw();\nrawTimestampSchema.validate('12376834097810'); // { error: null, value: '12376834097810' }\n```\n\n#### `any.required()` - aliases: `exist`\n\nMarks a key as required which will not allow `undefined` as value. All keys are optional by default.\n\n```js\nconst schema = Joi.any().required();\n```\n\nPossible validation errors: [`any.required`](#anyrequired)\n\n#### `any.result(mode)`\n\nSet the result mode where:\n- `mode` - one of `'raw'` (same as `any.raw()`) or `'strip'` (same as `any.strip()`).\n\n#### `any.rule(options)`\n\nApplies a set of rule options to the current ruleset or last rule added where:\n- `options` - the rules to apply where:\n  - `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`.\n  - `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.\n  - `warn` - if `true`, turns any error generated by the ruleset to warnings.\n\nWhen 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.\n\nRule 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.\n\n#### `any.ruleset` - aliases: `$`\n\nStarts a ruleset in order to apply multiple [rule options](#anyruleoptions). The set ends when\n[`rule()`](#anyruleoptions), [`keep()`](#anykeep), [`message()`](#anymessagemessage), or [`warn()`](#anywarn) is called.\n\n```js\nconst schema = Joi.number().ruleset.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n```js\nconst schema = Joi.number().$.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n#### `any.shared(schema)`\n\nRegisters a schema to be used by descendants of the current schema in named link references, where:\n- `schema` - a **joi** schema with an id.\n\n```js\n  const schema = Joi.object({\n      a: [Joi.string(), Joi.link('#x')],\n      b: Joi.link('#type.a')\n  })\n      .shared(Joi.number().id('x'))\n      .id('type');\n```\n\n#### `any.strict(isStrict)`\n\nStrict mode sets the `options.convert` options to `false` which prevent type casting for the current key and any child keys.\n- `isStrict` - whether strict mode is enabled or not. Defaults to true.\n\n```js\nconst schema = Joi.any().strict();\n```\n\n#### `any.strip([enabled])`\n\nMarks a key to be removed from a resulting object or array after validation to sanitize the output\nwhere:\n- `enabled` - if `true`, the value is stripped, otherwise the validated value is retained. Defaults\n  to `true`.\n\n```js\nconst schema = Joi.object({\n    username: Joi.string(),\n    password: Joi.string().strip()\n});\n\nschema.validate({ username: 'test', password: 'hunter2' }); // result.value = { username: 'test' }\n\nconst schema = Joi.array().items(Joi.string(), Joi.any().strip());\n\nschema.validate(['one', 'two', true, false, 1, 2]); // result.value = ['one', 'two']\n```\n\n#### `any.tag(...tags)`\n\nAnnotates the key where:\n- `tags` - the tag string or multiple tags (each as an argument).\n\n```js\nconst schema = Joi.any().tag('api', 'user');\n```\n\n#### `any.tailor(targets)`\n\nApplies any assigned target alterations to a copy of the schema that were applied via\n[`any.alter()`](#anyaltertargets) where:\n- `targets` - a single target string or array or target strings to apply.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor(['post']);\n```\n\n#### `any.unit(name)`\n\nAnnotates the key where:\n- `name` - the unit name of the value.\n\n```js\nconst schema = Joi.number().unit('milliseconds');\n```\n\n#### `any.valid(...values)` - aliases: `equal`\n\nAdds the provided values into the allowed values list and marks them as the only valid values allowed where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().valid('a'),\n    b: Joi.any().valid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.only`](#anyonly)\n\n#### `any.validate(value, [options])`\n\nValidates a value using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object with the following optional keys:\n  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.\n  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.\n  - `cache` - when `true`, schema caching is enabled (for schemas with explicit caching rules). Default to `true`.\n  - `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()`.\n  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.\n  - `dateFormat` - sets the string format used when converting dates to strings in error messages and casting. Options are:\n    - `'date'` - date string.\n    - `'iso'` - date time ISO string. This is the default.\n    - `'string'` - JS default date time string.\n    - `'time'` - time string.\n    - `'utc'` - UTC date time string.\n  - `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`.\n  - `errors` - error formatting settings:\n    - `escapeHtml` - when `true`, error message templates will escape special characters to HTML entities, for security purposes. Defaults to `false`.\n    - `label` - defines the value used to set the `label` context variable:\n      - `'path'` - the full path to the value being validated. This is the default value.\n      - `'key'` - the key of the value being validated.\n      - `false` - remove any label prefix from error message, including the `\"\"`.\n    - `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')`);\n    - `render` - when `false`, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time. Defaults to `true`.\n    - `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).\n    - `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:\n        - `label` - the characters used around `{#label}` references. Defaults to `'\"'`.\n        - `array` - the characters used around array values. Defaults to `'[]'`.\n        - `string` - the characters used around each array string values. Defaults to `false`.\n    - `wrapArrays` - if `true`, array values in error messages are wrapped in `[]`. Defaults to `true`.\n  - `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`.\n  - `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`.\n  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.\n  - `nonEnumerables` - when `true`, inputs are shallow cloned to include non-enumerable properties. Defaults to `false`.\n  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`. Defaults to `'optional'`.\n  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.\n  - `stripUnknown` - remove unknown elements from objects and arrays. Defaults to `false`.\n    - when an `object` :\n      - `arrays` - set to `true` to remove unknown items from arrays.\n      - `objects` - set to `true` to remove unknown keys from objects.\n    - when `true`, it is equivalent to having `{ arrays: false, objects: true }`.\n\nReturns an object with the following keys:\n- `value` - the validated and normalized value.\n- `error` - the validation errors if found.\n- `warning` - the generated warnings if any.\n- `artifacts` - a `Map` containing any passing rules' artifacts and their corresponding array of paths.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\nconst result = schema.validate(value);\n// result -> { value: { \"a\" : 123 } }\n```\n\n#### `any.validateAsync(value, [options])`\n\nValidates a value asynchronously using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object as described in [`any.validate()`](#anyvalidatevalue-options), with the following additional settings:\n    - `artifacts` - when `true`, artifacts are returned alongside the value (i.e. `{ value, artifacts }`). Defaults to `false`.\n    - `warnings` - when `true`, warnings are returned alongside the value (i.e. `{ value, warning }`). Defaults to `false`.\n\nReturns 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.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\ntry {\n  const value = await schema.validateAsync(value);\n  // value -> { \"a\" : 123 }\n}\ncatch (err) {\n}\n```\n\n#### `any.warn()`\n\nSame as [`rule({ warn: true })`](#anyruleoptions).\n\nNote that `warn()` will terminate the current ruleset and cannot be followed by another rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.warning(code, [context])`\n\nGenerates a warning where:\n- `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.\n- `context` - optional context object.\n\nWhen 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).\n\n```js\nconst schema = Joi.any()\n    .warning('custom.x', { w: 'world' })\n    .message({ 'custom.x': 'hello {#w}!' });\n\nconst { value, error, warning } = schema.validate('anything');\n\n// value -> 'anything';\n// error -> null\n// warning -> { message: 'hello world!', details: [...] }\n\n// or\n\ntry {\n    const { value, warning } = await schema.validateAsync('anything', { warnings: true });\n    // value -> 'anything';\n    // warning -> { message: 'hello world!', details: [...] }\n}\ncatch (err) { }\n```\n\n#### `any['~standard']`\n\nProvides compatibility with the [Standard Schema](https://github.com/standard-schema/spec) specification. It contains a `jsonSchema` object with the following methods:\n\n- `input([options])` - returns the JSON "},"items":[{"name":"API.md","path":"API.md","rawUrl":"https://raw.githubusercontent.com/hapijs/joi/HEAD/API.md","title":"API Interface Contract & Specifications","category":"project-spec","format":"markdown","content":"\n### Introduction\n\n**joi** lets you describe your data using a simple, intuitive, and readable language.\n\n#### Example\n\n```js\nconst Joi = require('joi');\n\nconst schema = Joi.object({\n    username: Joi.string()\n        .alphanum()\n        .min(3)\n        .max(30)\n        .required(),\n\n    password: Joi.string()\n        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),\n\n    repeat_password: Joi.ref('password'),\n\n    access_token: [\n        Joi.string(),\n        Joi.number()\n    ],\n\n    birth_year: Joi.number()\n        .integer()\n        .min(1900)\n        .max(2013),\n\n    email: Joi.string()\n        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n})\n    .with('username', 'birth_year')\n    .xor('password', 'access_token')\n    .with('password', 'repeat_password');\n\n\nschema.validate({ username: 'abc', birth_year: 1994 });\n// -> { value: { username: 'abc', birth_year: 1994 } }\n\nschema.validate({});\n// -> { value: {}, error: '\"username\" is required' }\n\n// Also -\n\ntry {\n    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });\n}\ncatch (err) { }\n```\n\nThe above schema defines the following constraints:\n* `username`\n    * a required string\n    * must contain only alphanumeric characters\n    * at least 3 characters long but no more than 30\n    * must be accompanied by `birth_year`\n* `password`\n    * an optional string\n    * must satisfy the custom regex pattern\n    * cannot appear together with `access_token`\n    * must be accompanied by `repeat_password` and equal to it\n* `access_token`\n    * an optional, unconstrained string or number\n* `birth_year`\n    * an integer between 1900 and 2013\n* `email`\n    * a valid email address string\n    * must have two domain parts e.g. `example.com`\n    * TLD must be `.com` or `.net`\n\n### General Usage\n\nUsage is a two steps process:\n\nFirst, a schema is constructed using the provided types and constraints:\n\n```js\nconst schema = Joi.object({\n    a: Joi.string()\n});\n```\n\nNote that **joi** schema objects are immutable which means every additional rule added (e.g.\n`.min(5)`) will return a new schema object.\n\nSecond, the value is validated against the defined schema:\n\n```js\nconst { error, value } = schema.validate({ a: 'a string' });\n```\n\nIf the input is valid, then the `error` will be `undefined`. If the input is invalid, `error` is assigned\na [`ValidationError`](#validationerror) object\nproviding more information.\n\nThe schema can be a plain JavaScript object where every key is assigned a **joi** type, or it can be a **joi** type directly:\n\n```js\nconst schema = Joi.string().min(10);\n```\n\nIf the schema is a **joi** type, the `schema.validate(value)` can be called directly on the type. When passing a non-type schema object,\nthe module converts it internally to an object() type equivalent to:\n\n```js\nconst schema = Joi.object().keys({\n    a: Joi.string()\n});\n```\n\nWhen validating a schema:\n\n* Values (or keys in case of objects) are optional by default.\n\n    ```js\n    Joi.string().validate(undefined); // validates fine\n    ```\n\n    To disallow this behavior, you can either set the schema as `required()`, or set `presence` to `\"required\"` when passing `options`:\n\n    ```js\n    Joi.string().required().validate(undefined);\n    // or\n    Joi.string().validate(undefined, /* options */ { presence: \"required\" });\n    ```\n\n* Strings are utf-8 encoded by default.\n* Rules are defined in an additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.\n\n### `assert(value, schema, [message], [options])`\n\nValidates a value against a schema and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.assert('x', Joi.number());\n```\n\n### `attempt(value, schema, [message], [options])`\n\nValidates a value against a schema, returns valid object, and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.attempt('x', Joi.number()); // throws error\nconst result = Joi.attempt('4', Joi.number()); // result -> 4\n```\n\n### `cache.provision([options])`\n\nProvisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and\nbooleans) where:\n- `options` - optional settings:\n    - `max` - number of items to store in the cache before the least used items are dropped.\n      Defaults to `1000`.\n\n### `checkPreferences(prefs)`\n\nChecks if the provided preferences are valid where:\n- `prefs` - the preferences object to validate.\n\nThrows an exception if the `prefs` object is invalid.\n\nThe method is provided to perform inputs validation for the [`any.validate()`](#anyvalidatevalue-options)\nand [`any.validateAsync()`](#anyvalidateasyncvalue-options) methods. Validation is not performed\nautomatically for performance reasons. Instead, manually validate the preferences passed once and\nreuse.\n\n### `compile(schema, [options])`\n\nConverts literal schema definition to **joi** schema object (or returns the same back if already a\n**joi** schema object) where:\n- `schema` - the schema definition to compile.\n- `options` - optional settings:\n    - `legacy` - if `true` and the provided schema is (or contains parts) using an older version of\n      **joi**, will return a compiled schema that is compatible with the older version. If `false`,\n      the schema is always compiled using the current version and if older schema components are\n      found, an error is thrown.\n\n```js\nconst definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];\nconst schema = Joi.compile(definition);\n\n// Same as:\n\nconst schema = Joi.alternatives().try(\n    Joi.string().valid('key'),\n    Joi.number().valid(5),\n    Joi.object({\n        a: Joi.boolean().valid(true),\n        b: Joi.alternatives().try(\n            Joi.string().pattern(/^a/),\n            Joi.string().valid('boom')\n        )\n    })\n);\n```\n\n### `defaults(modifier)`\n\nCreates a new **joi** instance that applies the provided modifier function to every new schemas\nwhere:\n- `modifier` - a function with signature `function(schema)` that must return a schema object.\n\n```js\nconst custom = Joi.defaults((schema) => {\n\n    switch (schema.type) {\n        case 'string':\n            return schema.allow('');\n        case 'object':\n            return schema.min(1);\n        default:\n            return schema;\n    }\n});\n\nconst schema = custom.object();   // Returns Joi.object().min(1)\n```\n\n### `expression(template, [options])` - aliases: `x`\n\nGenerates a dynamic expression using a template string where:\n- `template` - the template string using the [template syntax](#template-syntax).\n- `options` - optional settings used when creating internal references. Supports the same options\n  as [`ref()`](#refkey-options), in addition to those options:\n  - `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.\n\n#### Template syntax\n\nThe 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`).\n\nIf 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.\n\nThe 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. `[.]`).\n\nThe 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).\n\nThe reference names can have one of the following prefixes:\n- `#` - 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.\n- `$` - 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).\n- any other variable references a key within the current value being validated.\n\nThe formula syntax also supports built-in functions:\n- `if(condition, then, otherwise)` - returns `then` when `condition` is truthy, otherwise `otherwise`.\n- `length(item)` - return the length of an array or string, the number of keys of an object, otherwise `null`.\n- `msg(code)` - embeds another error code message.\n- `number(value)` - cast value to a number.\n\nAnd the following constants:\n- `null`\n- `true`\n- `false`\n\n### `extend(...extensions)`\n\nCreates a new customized instance of the **joi** module where:\n- `extensions` - the extensions configurations as described in [Extensions](#extensions).\n\nNote that the original **joi** module is not modified by this.\n\n### `in(ref, [options])`\n\nCreates a [reference](#refkey-options) that when resolved, is used as an array of values to match against the rule, where:\n- `ref` - same as [`Joi.ref()`](#refkey-options).\n- `options` - same as [`Joi.ref()`](#refkey-options).\n\nCan only be used in rules that support in-references.\n\n```js\nconst schema = Joi.object({\n    a: Joi.array().items(Joi.number()),\n    b: Joi.number().valid(Joi.in('a'))\n});\n```\n\n### `isError(err)`\n\nChecks whether or not the provided argument is a validation error.\n\n```js\nJoi.isError(new Error()); // returns false\n```\n\n### `isExpression(expression)`\n\nChecks whether or not the provided argument is an expression.\n\n```js\nconst expression = Joi.x('{a}');\nJoi.isExpression(expression); // returns true\n```\n\n### `isRef(ref)`\n\nChecks whether or not the provided argument is a reference. Useful if you want to post-process error messages.\n\n```js\nconst ref = Joi.ref('a');\nJoi.isRef(ref); // returns true\n```\n\n### `isSchema(schema, [options])`\n\nChecks whether or not the provided argument is a **joi** schema where:\n- `schema` - the value being checked.\n- `options` - optional settings:\n    - `legacy` - if `true`, will identify schemas from older versions of joi, otherwise will throw an error. Defaults to `false`.\n\n```js\nconst schema = Joi.any();\nJoi.isSchema(schema); // returns true\n```\n\n### `override`\n\nA special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.\n\n```js\nJoi.valid(1).valid(Joi.override, 2);\n\n// Same as:\n\nJoi.valid(2);\n\n// Whereas:\n\nJoi.valid(1).valid(2);\n\n// Is the same as:\n\nJoi.valid(1, 2);\n```\n\n### `ref(key, [options])`\n\nGenerates 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.\n\nReferences support the following arguments:\n- `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).\n- `options` - optional settings:\n    - `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`.\n    - `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`.\n    - `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:\n      - `global` - references to the globally provided `context` preference. Defaults to `'$'`.\n      - `local` - references to error-specific or rule specific context. Defaults to `'#'`.\n      - `root` - references to the root value being validated. Defaults to `'/'`.\n    - `separator` - overrides the default `.` hierarchy separator. Set to `false` to treat the `key` as a literal value.\n    - `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).\n    - `in` - creates an [in-reference](#inref-options).\n    - `iterables` - when `true`, the reference resolves by reaching into maps and sets.\n    - `render` - when `true`, the value of the reference is used instead of its name in error messages and template rendering. Defaults to `false`.\n\nNote 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).\n\n```js\nconst schema = Joi.object({\n    a: Joi.ref('b.c'),\n    b: {\n        c: Joi.any()\n    },\n    c: Joi.ref('$x')\n});\n\nawait schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } });\n```\n\n#### Relative references\n\nBy default, a reference is relative to the parent of the current value (the reference key is lookup\nup inside the parent). This means that in the schema:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nThe reference `Joi.ref('c')` points to `c` which is a sibling of `d` - the reference starting point\nis `d`'s parent which is `b`. This schema means that `d` must be equal to `c`.\n\nIn order to reference a parent peer, you can use a separator prefix where (using `.` as separator):\n- `.` - self\n- `..` - parent (same as no prefix)\n- `...` - grandparent\n- `....` - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c'),\n            e: Joi.ref('...a'),\n            f: Joi.ref('....y')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nAnother way to specify the relative starting point is using the `ancestor` option where:\n- 0 - self\n- 1 - parent (this is the default value if no key prefix is present)\n- 2 - grandparent\n- 3 - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c', { ancestor: 1 }),\n            e: Joi.ref('a', { ancestor: 2 }),\n            f: Joi.ref('y', { ancestor: 3 })\n        }\n    },\n    y: Joi.any()\n}\n```\n\nNote that if a reference tries to reach beyond the value root, validation fails.\n\nTo specify an absolute path from the value root, use the `/` prefix:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.ref('/x.a')\n        }\n    }\n}\n```\n\n### `version`\n\nProperty showing the current version of **joi** being used.\n\n### `types()`\n\nReturns an object where each key is a plain joi schema type. Useful for creating type shortcuts\nusing deconstruction. Note that the types are already formed and do not need to be called as\nfunctions (e.g. `string`, not `string()`).\n\n```js\nconst Joi = require('joi');\nconst { object, string } = Joi.types();\n\nconst schema = object.keys({\n  property: string.min(4)\n});\n```\n\n### `any`\n\nGenerates a schema object that matches any data type.\n\n```js\nconst any = Joi.any();\nawait any.validateAsync('a');\n```\n\n#### `any.type`\n\nGets the type of the schema.\n\n```js\nconst schema = Joi.string();\n\nschema.type === 'string';   // === true\n```\n\n#### `any.allow(...values)`\n\nAllows values where:\n- `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.\n\nNote that this list of allowed values is in *addition* to any other permitted values.\nTo create an exclusive list of values, see [`any.valid(value)`](#anyvalidvalues---aliases-equal).\n\n```js\nconst schema = {\n    a: Joi.any().allow('a'),\n    b: Joi.any().allow('b', 'B')\n};\n```\n\n#### `any.alter(targets)`\n\nAssign target alteration options to a schema that are applied when [`any.tailor()`](#anytailortargets)\nis called where:\n- `targets` - an object where each key is a target name, and each value is a function with signature\n  `function(schema)` that returns a schema.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor('post');\n```\n\n#### `any.artifact(id)`\n\nAssigns the schema an artifact id which is included in the validation result if the rule passed validation where:\n- `id` - any value other than `undefined` which will be returned as-is in the result `artifacts` map.\n\n```js\nconst schema = {\n    a: [\n        Joi.number().max(10).artifact('under'),\n        Joi.number().min(11).artifact('over')\n    ]\n};\n```\n\n#### `any.cache([cache])`\n\nAdds caching to the schema which will attempt to cache the validation results (success and\nfailures) of incoming inputs where:\n- `cache` - an optional cache implementation compatible with the built-in cache provided by\n  [`cache.provision()`](#cacheprovisionoptions). If no `cache` is passed, a default cache\n  is provisioned by using [`cache.provision()`](#cacheprovisionoptions) internally.\n\nNote that deciding which inputs to cache is left to the cache implementation. The built-in\ncache will only store simple values such as `undefined`, `null`, strings, numbers, and booleans.\nAny changes to the schema after `any.cache()` is called will disable caching on the resulting\nschema. this means that if `.cache()` is not the last statement in a schema definition, caching\nwill be disabled.\n\nTo disable caching for an entire schema in runtime, pass the `cache` preference set to `false`.\n\nCaching ignores changes to runtime preference. This means that if you run `schema.validate()`\nonces using one set of preferences, and then again using another set (for example, changing the\nlanguage), the cached results will be based on the first set of preferences.\n\nBefore using caching, it is recommended to consider the performance gain as it will not speed up\nevery schema. Schemas using `.valid()` list will not benefit from caching.\n\nCaching will be ignored when the schema uses references outside of the value scope.\n\n##### Cache interface\n\nCustom cache implementation must implement the following interface:\n\n```js\nclass {\n    set(key, value) {}\n    get(key) { return found ? value : undefined; }\n}\n```\n\nNote 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.\n\n#### `any.cast(to)`\n\nCasts the validated value to the specified type where:\n- `to` - the value target type. Each **joi** schema type supports its own set of cast targets:\n    - `'map'` - supported by the `Joi.object()` type, converts the result to a `Map` object containing the object key-value pairs.\n    - `'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`.\n    - `'set'` - supported by the `Joi.array()` type, converts the result to a `Set` object containing the array values.\n    - `'string'` - supported by `Joi.binary()`, `Joi.boolean()`, `Joi.date()`, and `Joi.number()`, converts the result to a string.\n\n#### `any.concat(schema)`\n\nReturns a new type that is the result of adding the rules of one type to another where:\n- `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.\n\n```js\nconst a = Joi.string().valid('a');\nconst b = Joi.string().valid('b');\nconst ab = a.concat(b);\n```\n\n#### `any.custom(method, [description])`\n\nAdds a custom validation function to execute arbitrary code where:\n- `method` - the custom (synchronous only) validation function using signature `function(value, helpers)` where:\n    - `value` - the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local], [localState])` - a method to generate error codes using a message code, optional local context and optional validation local state.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n\nNote: if the method fails to return a value, the value will be unset or returned as `undefined`.\n\n```js\nconst method = (value, helpers) => {\n\n    // Throw an error (will be replaced with 'any.custom' error)\n    if (value === '1') {\n        throw new Error('nope');\n    }\n\n    // Replace value with a new value\n    if (value === '2') {\n        return '3';\n    }\n\n    // Use error to return an existing error code\n    if (value === '4') {\n        return helpers.error('any.invalid');\n    }\n\n    // Override value with undefined to unset\n    if (value === '5') {\n        return undefined;\n    }\n\n    // Return the value unchanged\n    return value;\n};\n\nconst schema = Joi.string().custom(method, 'custom validation');\n```\n\nPossible validation errors: [`any.custom`](#anycustom)\n\n#### `any.default([value])`\n\nSets a default value if the original value is `undefined` where:\n- `value` - the default value. One of:\n    - a literal value (string, number, object, etc.).\n    - a [references](#refkey-options).\n    - a function which returns the default value using the signature `function(parent, helpers)` where:\n        - `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.\n        - `helpers` - same as those described in [`any.custom()`](#anycustommethod_description).\n\nWhen 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.\n\nNote 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).\n\n```js\nconst generateUsername = (parent, helpers) => {\n\n  return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase();\n};\n\ngenerateUsername.description = 'generated username';\n\nconst schema = Joi.object({\n    username: Joi.string().default(generateUsername),\n    firstname: Joi.string(),\n    lastname: Joi.string(),\n    created: Joi.date().default(Date.now),\n    status: Joi.string().default('registered')\n});\n\nconst { value } = schema.validate({\n    firstname: 'Jane',\n    lastname: 'Doe'\n});\n\n// value.status === 'registered'\n// value.username === 'jane-doe'\n// value.created will be the time of validation\n```\n\nPossible validation errors: [`any.default`](#anydefault)\n\n#### `any.describe()`\n\nReturns an object that represents the internal configuration of the schema. Useful for debugging\nand exposing a schema's configuration to other systems, like valid values in a user interface.\n\n```js\nconst schema = Joi.any().valid('foo', 'bar');\nconsole.log(schema.describe());\n```\n\nResults in:\n\n```\n{ type: 'any',\n  flags: { only: true },\n  valids: [ 'foo', 'bar' ] }\n```\n\n#### `any.description(desc)`\n\nAnnotates the key where:\n- `desc` - the description string.\n\n```js\nconst schema = Joi.any().description('this key will match anything you give it');\n```\n\n#### `any.empty(schema)`\n\nConsiders anything that matches the schema to be empty (`undefined`). Overrides any previous calls to empty.\n- `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.\n\n```js\nlet schema = Joi.string().empty('');\nschema.validate(''); // returns { error: null, value: undefined }\nschema = schema.empty();\nschema.validate(''); // returns { error: \"value\" is not allowed to be empty, value: '' }\n```\n\n#### `any.error(err)`\n\nOverrides the default **joi** error with a custom error if the rule fails where:\n- `err` can be:\n  - an instance of `Error` - the override error.\n  - 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.\n\nDo 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.\n\nNote 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.\n\n```js\nconst schema = Joi.string().error(new Error('Was REALLY expecting a string'));\nschema.validate(3);     // returns Error('Was REALLY expecting a string')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => new Error('\"foo\" requires a positive number'))\n});\nschema.validate({ foo: -2 });    // returns new Error('\"foo\" requires a positive number')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => {\n\n        return new Error('found errors with ' + errors.map((err) => `${err.local.key}(${err.local.limit}) with value ${err.local.value}`).join(' and '));\n    })\n});\nschema.validate({ foo: -2 });    // returns new Error('found errors with foo(0) with value -2')\n```\n\n#### `any.example(example, [options])`\n\nAdds examples to the schema where:\n- `example` - adds an example. Note that no validation is performed on the value.\n- `options` - optional settings:\n    - `override` - if `true`, replaces any existing examples. Defaults to `false`.\n\n```js\nconst schema = Joi.string().min(4).example('abcd');\n```\n\n#### `any.external(method, [description])`\n\nAdds an external validation rule where:\n- `method` - an async or sync function with signature `function(value, helpers)` which can either\n  return a replacement value, `undefined` to indicate no change, or throw an error, where:\n    - `value` - a clone of the object containing the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `linked` - if the schema is a link, the schema it links to.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local])` - a method to generate error codes using a message code and optional local context.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n- `description` - optional string used to document the purpose of the method.\n\nNote that external validation rules are only called after the all other validation rules for the\nentire schema (from the value root) are checked. This means that any changes made to the value by\nthe external rules are not available to any other validation rules during the non-external\nvalidation phase.\n\nIf schema validation failed, no external validation rules are called.\n\n#### `any.extract(path)`\n\nReturns a sub-schema based on a path of object keys or schema ids where:\n- `path` - a dot `.` separated path string or a pre-split array of path keys. The keys must match\n  the sub-schema id or object key (if no id was explicitly set).\n\n```js\nconst schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });\nconst number = schema.extract('foo.bar');\n\n//or\nconst result = schema.extract(['foo', 'bar']); //same as number\n```\n\n#### `any.failover(value)`\n\nSets a failover value if the original value fails passing validation where:\n- `value` - the failover value. `value` supports [references](#refkey-options). `value` may be\n  assigned a function which returns the default value. If `value` is specified as a function\n  that accepts a single parameter, that parameter will be a context object that can be used to\n  derive the resulting value.\n\nNote that if `value` is an object, any changes to the object after `failover()` is called will change\nthe reference and any future assignment. Use a function when setting a dynamic value (e.g. the\ncurrent time).\n\nUsing a function with a single argument performs some internal cloning which has a performance\nimpact. If you do not need access to the context, define the function without any arguments.\n\nPossible validation errors: [`any.failover`](#anyfailover)\n\n#### `any.forbidden()`\n\nMarks a key as forbidden which will not allow any value except `undefined`. Used to explicitly forbid keys.\n\n```js\nconst schema = {\n    a: Joi.any().forbidden()\n};\n```\n\nPossible validation errors: [`any.unknown`](#anyunknown)\n\n#### `any.fork(paths, adjuster)`\n\nReturns a new schema where each of the path keys listed have been modified where:\n- `paths` - an array of key strings, a single key string, or an array of arrays of pre-split\n  key strings. Key string paths use dot `.` to indicate key hierarchy.\n- `adjuster` - a function using the signature `function(schema)` which must return a modified\n  schema. For example, `(schema) => schema.required()`.\n\nThe method does not modify the original schema.\n\n#### `any.id(id)`\n\nSets a schema id for reaching into the schema via [`any.extract()`](#anyextractpath) where:\n- `id` - an alphanumeric string (plus `_`) used to identify the schema.\n\nIf no id is set, the schema id defaults to the object key it is associated with. If the schema is\nused in an array or alternatives type and no id is set, the schema is unreachable.\n\n#### `any.invalid(...values)` - aliases: `disallow`, `not`\n\nDisallows values where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().invalid('a'),\n    b: Joi.any().invalid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.invalid`](#anyinvalid)\n\n#### `any.isAsync()`\n\nReturns a boolean indicating whether this schema contains a rule that requires asynchronous validation.\n\n#### `any.keep()`\n\nSame as [`rule({ keep: true })`](#anyruleoptions).\n\nNote that `keep()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.label(name)`\n\nOverrides the key name in error messages.\n- `name` - the name of the key.\n\n```js\nconst schema = {\n    first_name: Joi.string().label('First Name')\n};\n```\n\n#### `any.message(message)`\n\nSame as [`rule({ message })`](#anyruleoptions).\n\nNote that `message()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.messages(messages)`\n\nSame as [`any.prefs({ messages })`](#anyprefsoptions---aliases-preferences-options).\n\nNote that while [`any.message()`](#anymessagemessage) applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.\n\n#### `any.meta(meta)`\n\nAttaches metadata to the key where:\n- `meta` - the meta object to attach.\n\n```js\nconst schema = Joi.any().meta({ index: true });\n```\n\n#### `any.note(...notes)`\n\nAnnotates the key where:\n- `notes` - the note string or multiple notes as individual arguments.\n\n```js\nconst schema = Joi.any().note('this is special', 'this is important');\n```\n\n#### `any.only()`\n\nRequires the validated value to match of the provided `any.allow()` values. It has no effect when\ncalled together with `any.valid()` since it already sets the requirements. When used with\n`any.allow()` it converts it to an `any.valid()`.\n\n#### `any.optional()`\n\nMarks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default.\n\nNote: this does not allow a `null` value. To do that, use [`any.allow(value)`](#anyallowvalue). Or both!\n\n```js\nconst schema = Joi.any().optional();\n```\n\n#### `any.prefs(options)` - aliases: `preferences`, `options`\n\nOverrides the global `validate()` options for the current key and any sub-key where:\n- `options` - an object with the same optional keys as [`any.validate()`](#anyvalidatevalue-options).\n\n```js\nconst schema = Joi.any().prefs({ convert: false });\n```\n\n#### `any.presence(mode)`\n\nSets the presence mode for the schema where:\n- `mode` - can be one of `'optional'`, `'required'`, or `'forbidden'`\n\nSame as calling `any.optional()`, `any.required()`, or `any.forbidden()`.\n\n#### `any.raw([enabled])`\n\nOutputs the original untouched value instead of the casted value where:\n- `enabled` - if `true`, the original result is returned, otherwise the validated value. Defaults to `true`.\n\nNote that the raw value is only applied after validation and any references to the value use the\nvalidated value, not the raw value.\n\n```js\nconst timestampSchema = Joi.date().timestamp();\ntimestampSchema.validate('12376834097810'); // { error: null, value: Sat Mar 17 2362 04:28:17 GMT-0500 (CDT) }\n\nconst rawTimestampSchema = Joi.date().timestamp().raw();\nrawTimestampSchema.validate('12376834097810'); // { error: null, value: '12376834097810' }\n```\n\n#### `any.required()` - aliases: `exist`\n\nMarks a key as required which will not allow `undefined` as value. All keys are optional by default.\n\n```js\nconst schema = Joi.any().required();\n```\n\nPossible validation errors: [`any.required`](#anyrequired)\n\n#### `any.result(mode)`\n\nSet the result mode where:\n- `mode` - one of `'raw'` (same as `any.raw()`) or `'strip'` (same as `any.strip()`).\n\n#### `any.rule(options)`\n\nApplies a set of rule options to the current ruleset or last rule added where:\n- `options` - the rules to apply where:\n  - `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`.\n  - `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.\n  - `warn` - if `true`, turns any error generated by the ruleset to warnings.\n\nWhen 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.\n\nRule 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.\n\n#### `any.ruleset` - aliases: `$`\n\nStarts a ruleset in order to apply multiple [rule options](#anyruleoptions). The set ends when\n[`rule()`](#anyruleoptions), [`keep()`](#anykeep), [`message()`](#anymessagemessage), or [`warn()`](#anywarn) is called.\n\n```js\nconst schema = Joi.number().ruleset.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n```js\nconst schema = Joi.number().$.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n#### `any.shared(schema)`\n\nRegisters a schema to be used by descendants of the current schema in named link references, where:\n- `schema` - a **joi** schema with an id.\n\n```js\n  const schema = Joi.object({\n      a: [Joi.string(), Joi.link('#x')],\n      b: Joi.link('#type.a')\n  })\n      .shared(Joi.number().id('x'))\n      .id('type');\n```\n\n#### `any.strict(isStrict)`\n\nStrict mode sets the `options.convert` options to `false` which prevent type casting for the current key and any child keys.\n- `isStrict` - whether strict mode is enabled or not. Defaults to true.\n\n```js\nconst schema = Joi.any().strict();\n```\n\n#### `any.strip([enabled])`\n\nMarks a key to be removed from a resulting object or array after validation to sanitize the output\nwhere:\n- `enabled` - if `true`, the value is stripped, otherwise the validated value is retained. Defaults\n  to `true`.\n\n```js\nconst schema = Joi.object({\n    username: Joi.string(),\n    password: Joi.string().strip()\n});\n\nschema.validate({ username: 'test', password: 'hunter2' }); // result.value = { username: 'test' }\n\nconst schema = Joi.array().items(Joi.string(), Joi.any().strip());\n\nschema.validate(['one', 'two', true, false, 1, 2]); // result.value = ['one', 'two']\n```\n\n#### `any.tag(...tags)`\n\nAnnotates the key where:\n- `tags` - the tag string or multiple tags (each as an argument).\n\n```js\nconst schema = Joi.any().tag('api', 'user');\n```\n\n#### `any.tailor(targets)`\n\nApplies any assigned target alterations to a copy of the schema that were applied via\n[`any.alter()`](#anyaltertargets) where:\n- `targets` - a single target string or array or target strings to apply.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor(['post']);\n```\n\n#### `any.unit(name)`\n\nAnnotates the key where:\n- `name` - the unit name of the value.\n\n```js\nconst schema = Joi.number().unit('milliseconds');\n```\n\n#### `any.valid(...values)` - aliases: `equal`\n\nAdds the provided values into the allowed values list and marks them as the only valid values allowed where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().valid('a'),\n    b: Joi.any().valid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.only`](#anyonly)\n\n#### `any.validate(value, [options])`\n\nValidates a value using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object with the following optional keys:\n  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.\n  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.\n  - `cache` - when `true`, schema caching is enabled (for schemas with explicit caching rules). Default to `true`.\n  - `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()`.\n  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.\n  - `dateFormat` - sets the string format used when converting dates to strings in error messages and casting. Options are:\n    - `'date'` - date string.\n    - `'iso'` - date time ISO string. This is the default.\n    - `'string'` - JS default date time string.\n    - `'time'` - time string.\n    - `'utc'` - UTC date time string.\n  - `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`.\n  - `errors` - error formatting settings:\n    - `escapeHtml` - when `true`, error message templates will escape special characters to HTML entities, for security purposes. Defaults to `false`.\n    - `label` - defines the value used to set the `label` context variable:\n      - `'path'` - the full path to the value being validated. This is the default value.\n      - `'key'` - the key of the value being validated.\n      - `false` - remove any label prefix from error message, including the `\"\"`.\n    - `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')`);\n    - `render` - when `false`, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time. Defaults to `true`.\n    - `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).\n    - `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:\n        - `label` - the characters used around `{#label}` references. Defaults to `'\"'`.\n        - `array` - the characters used around array values. Defaults to `'[]'`.\n        - `string` - the characters used around each array string values. Defaults to `false`.\n    - `wrapArrays` - if `true`, array values in error messages are wrapped in `[]`. Defaults to `true`.\n  - `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`.\n  - `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`.\n  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.\n  - `nonEnumerables` - when `true`, inputs are shallow cloned to include non-enumerable properties. Defaults to `false`.\n  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`. Defaults to `'optional'`.\n  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.\n  - `stripUnknown` - remove unknown elements from objects and arrays. Defaults to `false`.\n    - when an `object` :\n      - `arrays` - set to `true` to remove unknown items from arrays.\n      - `objects` - set to `true` to remove unknown keys from objects.\n    - when `true`, it is equivalent to having `{ arrays: false, objects: true }`.\n\nReturns an object with the following keys:\n- `value` - the validated and normalized value.\n- `error` - the validation errors if found.\n- `warning` - the generated warnings if any.\n- `artifacts` - a `Map` containing any passing rules' artifacts and their corresponding array of paths.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\nconst result = schema.validate(value);\n// result -> { value: { \"a\" : 123 } }\n```\n\n#### `any.validateAsync(value, [options])`\n\nValidates a value asynchronously using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object as described in [`any.validate()`](#anyvalidatevalue-options), with the following additional settings:\n    - `artifacts` - when `true`, artifacts are returned alongside the value (i.e. `{ value, artifacts }`). Defaults to `false`.\n    - `warnings` - when `true`, warnings are returned alongside the value (i.e. `{ value, warning }`). Defaults to `false`.\n\nReturns 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.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\ntry {\n  const value = await schema.validateAsync(value);\n  // value -> { \"a\" : 123 }\n}\ncatch (err) {\n}\n```\n\n#### `any.warn()`\n\nSame as [`rule({ warn: true })`](#anyruleoptions).\n\nNote that `warn()` will terminate the current ruleset and cannot be followed by another rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.warning(code, [context])`\n\nGenerates a warning where:\n- `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.\n- `context` - optional context object.\n\nWhen 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).\n\n```js\nconst schema = Joi.any()\n    .warning('custom.x', { w: 'world' })\n    .message({ 'custom.x': 'hello {#w}!' });\n\nconst { value, error, warning } = schema.validate('anything');\n\n// value -> 'anything';\n// error -> null\n// warning -> { message: 'hello world!', details: [...] }\n\n// or\n\ntry {\n    const { value, warning } = await schema.validateAsync('anything', { warnings: true });\n    // value -> 'anything';\n    // warning -> { message: 'hello world!', details: [...] }\n}\ncatch (err) { }\n```\n\n#### `any['~standard']`\n\nProvides compatibility with the [Standard Schema](https://github.com/standard-schema/spec) specification. It contains a `jsonSchema` object with the following methods:\n\n- `input([options])` - returns the JSON ","isInternal":false,"tokens":11985,"sizeBytes":50000}],"systemPromptSnippet":"<yakaai_skills repo=\"hapijs/joi\">\n<!-- File: API.md (Tokens: ~11985 | Category: project-spec) -->\n### Introduction\n\n**joi** lets you describe your data using a simple, intuitive, and readable language.\n\n#### Example\n\n```js\nconst Joi = require('joi');\n\nconst schema = Joi.object({\n    username: Joi.string()\n        .alphanum()\n        .min(3)\n        .max(30)\n        .required(),\n\n    password: Joi.string()\n        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),\n\n    repeat_password: Joi.ref('password'),\n\n    access_token: [\n        Joi.string(),\n        Joi.number()\n    ],\n\n    birth_year: Joi.number()\n        .integer()\n        .min(1900)\n        .max(2013),\n\n    email: Joi.string()\n        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })\n})\n    .with('username', 'birth_year')\n    .xor('password', 'access_token')\n    .with('password', 'repeat_password');\n\n\nschema.validate({ username: 'abc', birth_year: 1994 });\n// -> { value: { username: 'abc', birth_year: 1994 } }\n\nschema.validate({});\n// -> { value: {}, error: '\"username\" is required' }\n\n// Also -\n\ntry {\n    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });\n}\ncatch (err) { }\n```\n\nThe above schema defines the following constraints:\n* `username`\n    * a required string\n    * must contain only alphanumeric characters\n    * at least 3 characters long but no more than 30\n    * must be accompanied by `birth_year`\n* `password`\n    * an optional string\n    * must satisfy the custom regex pattern\n    * cannot appear together with `access_token`\n    * must be accompanied by `repeat_password` and equal to it\n* `access_token`\n    * an optional, unconstrained string or number\n* `birth_year`\n    * an integer between 1900 and 2013\n* `email`\n    * a valid email address string\n    * must have two domain parts e.g. `example.com`\n    * TLD must be `.com` or `.net`\n\n### General Usage\n\nUsage is a two steps process:\n\nFirst, a schema is constructed using the provided types and constraints:\n\n```js\nconst schema = Joi.object({\n    a: Joi.string()\n});\n```\n\nNote that **joi** schema objects are immutable which means every additional rule added (e.g.\n`.min(5)`) will return a new schema object.\n\nSecond, the value is validated against the defined schema:\n\n```js\nconst { error, value } = schema.validate({ a: 'a string' });\n```\n\nIf the input is valid, then the `error` will be `undefined`. If the input is invalid, `error` is assigned\na [`ValidationError`](#validationerror) object\nproviding more information.\n\nThe schema can be a plain JavaScript object where every key is assigned a **joi** type, or it can be a **joi** type directly:\n\n```js\nconst schema = Joi.string().min(10);\n```\n\nIf the schema is a **joi** type, the `schema.validate(value)` can be called directly on the type. When passing a non-type schema object,\nthe module converts it internally to an object() type equivalent to:\n\n```js\nconst schema = Joi.object().keys({\n    a: Joi.string()\n});\n```\n\nWhen validating a schema:\n\n* Values (or keys in case of objects) are optional by default.\n\n    ```js\n    Joi.string().validate(undefined); // validates fine\n    ```\n\n    To disallow this behavior, you can either set the schema as `required()`, or set `presence` to `\"required\"` when passing `options`:\n\n    ```js\n    Joi.string().required().validate(undefined);\n    // or\n    Joi.string().validate(undefined, /* options */ { presence: \"required\" });\n    ```\n\n* Strings are utf-8 encoded by default.\n* Rules are defined in an additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.\n\n### `assert(value, schema, [message], [options])`\n\nValidates a value against a schema and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.assert('x', Joi.number());\n```\n\n### `attempt(value, schema, [message], [options])`\n\nValidates a value against a schema, returns valid object, and [throws](#errors) if validation fails where:\n- `value` - the value to validate.\n- `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).\n- `message` - optional message string prefix added in front of the error message. may also be an Error object.\n- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)\n\n```js\nJoi.attempt('x', Joi.number()); // throws error\nconst result = Joi.attempt('4', Joi.number()); // result -> 4\n```\n\n### `cache.provision([options])`\n\nProvisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and\nbooleans) where:\n- `options` - optional settings:\n    - `max` - number of items to store in the cache before the least used items are dropped.\n      Defaults to `1000`.\n\n### `checkPreferences(prefs)`\n\nChecks if the provided preferences are valid where:\n- `prefs` - the preferences object to validate.\n\nThrows an exception if the `prefs` object is invalid.\n\nThe method is provided to perform inputs validation for the [`any.validate()`](#anyvalidatevalue-options)\nand [`any.validateAsync()`](#anyvalidateasyncvalue-options) methods. Validation is not performed\nautomatically for performance reasons. Instead, manually validate the preferences passed once and\nreuse.\n\n### `compile(schema, [options])`\n\nConverts literal schema definition to **joi** schema object (or returns the same back if already a\n**joi** schema object) where:\n- `schema` - the schema definition to compile.\n- `options` - optional settings:\n    - `legacy` - if `true` and the provided schema is (or contains parts) using an older version of\n      **joi**, will return a compiled schema that is compatible with the older version. If `false`,\n      the schema is always compiled using the current version and if older schema components are\n      found, an error is thrown.\n\n```js\nconst definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];\nconst schema = Joi.compile(definition);\n\n// Same as:\n\nconst schema = Joi.alternatives().try(\n    Joi.string().valid('key'),\n    Joi.number().valid(5),\n    Joi.object({\n        a: Joi.boolean().valid(true),\n        b: Joi.alternatives().try(\n            Joi.string().pattern(/^a/),\n            Joi.string().valid('boom')\n        )\n    })\n);\n```\n\n### `defaults(modifier)`\n\nCreates a new **joi** instance that applies the provided modifier function to every new schemas\nwhere:\n- `modifier` - a function with signature `function(schema)` that must return a schema object.\n\n```js\nconst custom = Joi.defaults((schema) => {\n\n    switch (schema.type) {\n        case 'string':\n            return schema.allow('');\n        case 'object':\n            return schema.min(1);\n        default:\n            return schema;\n    }\n});\n\nconst schema = custom.object();   // Returns Joi.object().min(1)\n```\n\n### `expression(template, [options])` - aliases: `x`\n\nGenerates a dynamic expression using a template string where:\n- `template` - the template string using the [template syntax](#template-syntax).\n- `options` - optional settings used when creating internal references. Supports the same options\n  as [`ref()`](#refkey-options), in addition to those options:\n  - `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.\n\n#### Template syntax\n\nThe 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`).\n\nIf 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.\n\nThe 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. `[.]`).\n\nThe 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).\n\nThe reference names can have one of the following prefixes:\n- `#` - 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.\n- `$` - 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).\n- any other variable references a key within the current value being validated.\n\nThe formula syntax also supports built-in functions:\n- `if(condition, then, otherwise)` - returns `then` when `condition` is truthy, otherwise `otherwise`.\n- `length(item)` - return the length of an array or string, the number of keys of an object, otherwise `null`.\n- `msg(code)` - embeds another error code message.\n- `number(value)` - cast value to a number.\n\nAnd the following constants:\n- `null`\n- `true`\n- `false`\n\n### `extend(...extensions)`\n\nCreates a new customized instance of the **joi** module where:\n- `extensions` - the extensions configurations as described in [Extensions](#extensions).\n\nNote that the original **joi** module is not modified by this.\n\n### `in(ref, [options])`\n\nCreates a [reference](#refkey-options) that when resolved, is used as an array of values to match against the rule, where:\n- `ref` - same as [`Joi.ref()`](#refkey-options).\n- `options` - same as [`Joi.ref()`](#refkey-options).\n\nCan only be used in rules that support in-references.\n\n```js\nconst schema = Joi.object({\n    a: Joi.array().items(Joi.number()),\n    b: Joi.number().valid(Joi.in('a'))\n});\n```\n\n### `isError(err)`\n\nChecks whether or not the provided argument is a validation error.\n\n```js\nJoi.isError(new Error()); // returns false\n```\n\n### `isExpression(expression)`\n\nChecks whether or not the provided argument is an expression.\n\n```js\nconst expression = Joi.x('{a}');\nJoi.isExpression(expression); // returns true\n```\n\n### `isRef(ref)`\n\nChecks whether or not the provided argument is a reference. Useful if you want to post-process error messages.\n\n```js\nconst ref = Joi.ref('a');\nJoi.isRef(ref); // returns true\n```\n\n### `isSchema(schema, [options])`\n\nChecks whether or not the provided argument is a **joi** schema where:\n- `schema` - the value being checked.\n- `options` - optional settings:\n    - `legacy` - if `true`, will identify schemas from older versions of joi, otherwise will throw an error. Defaults to `false`.\n\n```js\nconst schema = Joi.any();\nJoi.isSchema(schema); // returns true\n```\n\n### `override`\n\nA special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.\n\n```js\nJoi.valid(1).valid(Joi.override, 2);\n\n// Same as:\n\nJoi.valid(2);\n\n// Whereas:\n\nJoi.valid(1).valid(2);\n\n// Is the same as:\n\nJoi.valid(1, 2);\n```\n\n### `ref(key, [options])`\n\nGenerates 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.\n\nReferences support the following arguments:\n- `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).\n- `options` - optional settings:\n    - `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`.\n    - `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`.\n    - `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:\n      - `global` - references to the globally provided `context` preference. Defaults to `'$'`.\n      - `local` - references to error-specific or rule specific context. Defaults to `'#'`.\n      - `root` - references to the root value being validated. Defaults to `'/'`.\n    - `separator` - overrides the default `.` hierarchy separator. Set to `false` to treat the `key` as a literal value.\n    - `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).\n    - `in` - creates an [in-reference](#inref-options).\n    - `iterables` - when `true`, the reference resolves by reaching into maps and sets.\n    - `render` - when `true`, the value of the reference is used instead of its name in error messages and template rendering. Defaults to `false`.\n\nNote 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).\n\n```js\nconst schema = Joi.object({\n    a: Joi.ref('b.c'),\n    b: {\n        c: Joi.any()\n    },\n    c: Joi.ref('$x')\n});\n\nawait schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } });\n```\n\n#### Relative references\n\nBy default, a reference is relative to the parent of the current value (the reference key is lookup\nup inside the parent). This means that in the schema:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nThe reference `Joi.ref('c')` points to `c` which is a sibling of `d` - the reference starting point\nis `d`'s parent which is `b`. This schema means that `d` must be equal to `c`.\n\nIn order to reference a parent peer, you can use a separator prefix where (using `.` as separator):\n- `.` - self\n- `..` - parent (same as no prefix)\n- `...` - grandparent\n- `....` - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c'),\n            e: Joi.ref('...a'),\n            f: Joi.ref('....y')\n        }\n    },\n    y: Joi.any()\n}\n```\n\nAnother way to specify the relative starting point is using the `ancestor` option where:\n- 0 - self\n- 1 - parent (this is the default value if no key prefix is present)\n- 2 - grandparent\n- 3 - great-grandparent\n- etc.\n\nFor example:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.any(),\n            d: Joi.ref('c', { ancestor: 1 }),\n            e: Joi.ref('a', { ancestor: 2 }),\n            f: Joi.ref('y', { ancestor: 3 })\n        }\n    },\n    y: Joi.any()\n}\n```\n\nNote that if a reference tries to reach beyond the value root, validation fails.\n\nTo specify an absolute path from the value root, use the `/` prefix:\n\n```js\n{\n    x: {\n        a: Joi.any(),\n        b: {\n            c: Joi.ref('/x.a')\n        }\n    }\n}\n```\n\n### `version`\n\nProperty showing the current version of **joi** being used.\n\n### `types()`\n\nReturns an object where each key is a plain joi schema type. Useful for creating type shortcuts\nusing deconstruction. Note that the types are already formed and do not need to be called as\nfunctions (e.g. `string`, not `string()`).\n\n```js\nconst Joi = require('joi');\nconst { object, string } = Joi.types();\n\nconst schema = object.keys({\n  property: string.min(4)\n});\n```\n\n### `any`\n\nGenerates a schema object that matches any data type.\n\n```js\nconst any = Joi.any();\nawait any.validateAsync('a');\n```\n\n#### `any.type`\n\nGets the type of the schema.\n\n```js\nconst schema = Joi.string();\n\nschema.type === 'string';   // === true\n```\n\n#### `any.allow(...values)`\n\nAllows values where:\n- `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.\n\nNote that this list of allowed values is in *addition* to any other permitted values.\nTo create an exclusive list of values, see [`any.valid(value)`](#anyvalidvalues---aliases-equal).\n\n```js\nconst schema = {\n    a: Joi.any().allow('a'),\n    b: Joi.any().allow('b', 'B')\n};\n```\n\n#### `any.alter(targets)`\n\nAssign target alteration options to a schema that are applied when [`any.tailor()`](#anytailortargets)\nis called where:\n- `targets` - an object where each key is a target name, and each value is a function with signature\n  `function(schema)` that returns a schema.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor('post');\n```\n\n#### `any.artifact(id)`\n\nAssigns the schema an artifact id which is included in the validation result if the rule passed validation where:\n- `id` - any value other than `undefined` which will be returned as-is in the result `artifacts` map.\n\n```js\nconst schema = {\n    a: [\n        Joi.number().max(10).artifact('under'),\n        Joi.number().min(11).artifact('over')\n    ]\n};\n```\n\n#### `any.cache([cache])`\n\nAdds caching to the schema which will attempt to cache the validation results (success and\nfailures) of incoming inputs where:\n- `cache` - an optional cache implementation compatible with the built-in cache provided by\n  [`cache.provision()`](#cacheprovisionoptions). If no `cache` is passed, a default cache\n  is provisioned by using [`cache.provision()`](#cacheprovisionoptions) internally.\n\nNote that deciding which inputs to cache is left to the cache implementation. The built-in\ncache will only store simple values such as `undefined`, `null`, strings, numbers, and booleans.\nAny changes to the schema after `any.cache()` is called will disable caching on the resulting\nschema. this means that if `.cache()` is not the last statement in a schema definition, caching\nwill be disabled.\n\nTo disable caching for an entire schema in runtime, pass the `cache` preference set to `false`.\n\nCaching ignores changes to runtime preference. This means that if you run `schema.validate()`\nonces using one set of preferences, and then again using another set (for example, changing the\nlanguage), the cached results will be based on the first set of preferences.\n\nBefore using caching, it is recommended to consider the performance gain as it will not speed up\nevery schema. Schemas using `.valid()` list will not benefit from caching.\n\nCaching will be ignored when the schema uses references outside of the value scope.\n\n##### Cache interface\n\nCustom cache implementation must implement the following interface:\n\n```js\nclass {\n    set(key, value) {}\n    get(key) { return found ? value : undefined; }\n}\n```\n\nNote 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.\n\n#### `any.cast(to)`\n\nCasts the validated value to the specified type where:\n- `to` - the value target type. Each **joi** schema type supports its own set of cast targets:\n    - `'map'` - supported by the `Joi.object()` type, converts the result to a `Map` object containing the object key-value pairs.\n    - `'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`.\n    - `'set'` - supported by the `Joi.array()` type, converts the result to a `Set` object containing the array values.\n    - `'string'` - supported by `Joi.binary()`, `Joi.boolean()`, `Joi.date()`, and `Joi.number()`, converts the result to a string.\n\n#### `any.concat(schema)`\n\nReturns a new type that is the result of adding the rules of one type to another where:\n- `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.\n\n```js\nconst a = Joi.string().valid('a');\nconst b = Joi.string().valid('b');\nconst ab = a.concat(b);\n```\n\n#### `any.custom(method, [description])`\n\nAdds a custom validation function to execute arbitrary code where:\n- `method` - the custom (synchronous only) validation function using signature `function(value, helpers)` where:\n    - `value` - the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local], [localState])` - a method to generate error codes using a message code, optional local context and optional validation local state.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n\nNote: if the method fails to return a value, the value will be unset or returned as `undefined`.\n\n```js\nconst method = (value, helpers) => {\n\n    // Throw an error (will be replaced with 'any.custom' error)\n    if (value === '1') {\n        throw new Error('nope');\n    }\n\n    // Replace value with a new value\n    if (value === '2') {\n        return '3';\n    }\n\n    // Use error to return an existing error code\n    if (value === '4') {\n        return helpers.error('any.invalid');\n    }\n\n    // Override value with undefined to unset\n    if (value === '5') {\n        return undefined;\n    }\n\n    // Return the value unchanged\n    return value;\n};\n\nconst schema = Joi.string().custom(method, 'custom validation');\n```\n\nPossible validation errors: [`any.custom`](#anycustom)\n\n#### `any.default([value])`\n\nSets a default value if the original value is `undefined` where:\n- `value` - the default value. One of:\n    - a literal value (string, number, object, etc.).\n    - a [references](#refkey-options).\n    - a function which returns the default value using the signature `function(parent, helpers)` where:\n        - `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.\n        - `helpers` - same as those described in [`any.custom()`](#anycustommethod_description).\n\nWhen 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.\n\nNote 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).\n\n```js\nconst generateUsername = (parent, helpers) => {\n\n  return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase();\n};\n\ngenerateUsername.description = 'generated username';\n\nconst schema = Joi.object({\n    username: Joi.string().default(generateUsername),\n    firstname: Joi.string(),\n    lastname: Joi.string(),\n    created: Joi.date().default(Date.now),\n    status: Joi.string().default('registered')\n});\n\nconst { value } = schema.validate({\n    firstname: 'Jane',\n    lastname: 'Doe'\n});\n\n// value.status === 'registered'\n// value.username === 'jane-doe'\n// value.created will be the time of validation\n```\n\nPossible validation errors: [`any.default`](#anydefault)\n\n#### `any.describe()`\n\nReturns an object that represents the internal configuration of the schema. Useful for debugging\nand exposing a schema's configuration to other systems, like valid values in a user interface.\n\n```js\nconst schema = Joi.any().valid('foo', 'bar');\nconsole.log(schema.describe());\n```\n\nResults in:\n\n```\n{ type: 'any',\n  flags: { only: true },\n  valids: [ 'foo', 'bar' ] }\n```\n\n#### `any.description(desc)`\n\nAnnotates the key where:\n- `desc` - the description string.\n\n```js\nconst schema = Joi.any().description('this key will match anything you give it');\n```\n\n#### `any.empty(schema)`\n\nConsiders anything that matches the schema to be empty (`undefined`). Overrides any previous calls to empty.\n- `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.\n\n```js\nlet schema = Joi.string().empty('');\nschema.validate(''); // returns { error: null, value: undefined }\nschema = schema.empty();\nschema.validate(''); // returns { error: \"value\" is not allowed to be empty, value: '' }\n```\n\n#### `any.error(err)`\n\nOverrides the default **joi** error with a custom error if the rule fails where:\n- `err` can be:\n  - an instance of `Error` - the override error.\n  - 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.\n\nDo 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.\n\nNote 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.\n\n```js\nconst schema = Joi.string().error(new Error('Was REALLY expecting a string'));\nschema.validate(3);     // returns Error('Was REALLY expecting a string')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => new Error('\"foo\" requires a positive number'))\n});\nschema.validate({ foo: -2 });    // returns new Error('\"foo\" requires a positive number')\n```\n\n```js\nconst schema = Joi.object({\n    foo: Joi.number().min(0).error((errors) => {\n\n        return new Error('found errors with ' + errors.map((err) => `${err.local.key}(${err.local.limit}) with value ${err.local.value}`).join(' and '));\n    })\n});\nschema.validate({ foo: -2 });    // returns new Error('found errors with foo(0) with value -2')\n```\n\n#### `any.example(example, [options])`\n\nAdds examples to the schema where:\n- `example` - adds an example. Note that no validation is performed on the value.\n- `options` - optional settings:\n    - `override` - if `true`, replaces any existing examples. Defaults to `false`.\n\n```js\nconst schema = Joi.string().min(4).example('abcd');\n```\n\n#### `any.external(method, [description])`\n\nAdds an external validation rule where:\n- `method` - an async or sync function with signature `function(value, helpers)` which can either\n  return a replacement value, `undefined` to indicate no change, or throw an error, where:\n    - `value` - a clone of the object containing the value being validated.\n    - `helpers` - an object with the following helpers:\n        - `schema` - the current schema.\n        - `linked` - if the schema is a link, the schema it links to.\n        - `state` - the current validation state.\n        - `prefs` - the current preferences.\n        - `original` - the original value passed into validation before any conversions.\n        - `error(code, [local])` - a method to generate error codes using a message code and optional local context.\n        - `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.\n        - `warn(code, [local])` - a method to add a warning using a message code and optional local context.\n- `description` - optional string used to document the purpose of the method.\n\nNote that external validation rules are only called after the all other validation rules for the\nentire schema (from the value root) are checked. This means that any changes made to the value by\nthe external rules are not available to any other validation rules during the non-external\nvalidation phase.\n\nIf schema validation failed, no external validation rules are called.\n\n#### `any.extract(path)`\n\nReturns a sub-schema based on a path of object keys or schema ids where:\n- `path` - a dot `.` separated path string or a pre-split array of path keys. The keys must match\n  the sub-schema id or object key (if no id was explicitly set).\n\n```js\nconst schema = Joi.object({ foo: Joi.object({ bar: Joi.number() }) });\nconst number = schema.extract('foo.bar');\n\n//or\nconst result = schema.extract(['foo', 'bar']); //same as number\n```\n\n#### `any.failover(value)`\n\nSets a failover value if the original value fails passing validation where:\n- `value` - the failover value. `value` supports [references](#refkey-options). `value` may be\n  assigned a function which returns the default value. If `value` is specified as a function\n  that accepts a single parameter, that parameter will be a context object that can be used to\n  derive the resulting value.\n\nNote that if `value` is an object, any changes to the object after `failover()` is called will change\nthe reference and any future assignment. Use a function when setting a dynamic value (e.g. the\ncurrent time).\n\nUsing a function with a single argument performs some internal cloning which has a performance\nimpact. If you do not need access to the context, define the function without any arguments.\n\nPossible validation errors: [`any.failover`](#anyfailover)\n\n#### `any.forbidden()`\n\nMarks a key as forbidden which will not allow any value except `undefined`. Used to explicitly forbid keys.\n\n```js\nconst schema = {\n    a: Joi.any().forbidden()\n};\n```\n\nPossible validation errors: [`any.unknown`](#anyunknown)\n\n#### `any.fork(paths, adjuster)`\n\nReturns a new schema where each of the path keys listed have been modified where:\n- `paths` - an array of key strings, a single key string, or an array of arrays of pre-split\n  key strings. Key string paths use dot `.` to indicate key hierarchy.\n- `adjuster` - a function using the signature `function(schema)` which must return a modified\n  schema. For example, `(schema) => schema.required()`.\n\nThe method does not modify the original schema.\n\n#### `any.id(id)`\n\nSets a schema id for reaching into the schema via [`any.extract()`](#anyextractpath) where:\n- `id` - an alphanumeric string (plus `_`) used to identify the schema.\n\nIf no id is set, the schema id defaults to the object key it is associated with. If the schema is\nused in an array or alternatives type and no id is set, the schema is unreachable.\n\n#### `any.invalid(...values)` - aliases: `disallow`, `not`\n\nDisallows values where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().invalid('a'),\n    b: Joi.any().invalid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.invalid`](#anyinvalid)\n\n#### `any.isAsync()`\n\nReturns a boolean indicating whether this schema contains a rule that requires asynchronous validation.\n\n#### `any.keep()`\n\nSame as [`rule({ keep: true })`](#anyruleoptions).\n\nNote that `keep()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.label(name)`\n\nOverrides the key name in error messages.\n- `name` - the name of the key.\n\n```js\nconst schema = {\n    first_name: Joi.string().label('First Name')\n};\n```\n\n#### `any.message(message)`\n\nSame as [`rule({ message })`](#anyruleoptions).\n\nNote that `message()` will terminate the current ruleset and cannot be followed by another\nrule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.messages(messages)`\n\nSame as [`any.prefs({ messages })`](#anyprefsoptions---aliases-preferences-options).\n\nNote that while [`any.message()`](#anymessagemessage) applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.\n\n#### `any.meta(meta)`\n\nAttaches metadata to the key where:\n- `meta` - the meta object to attach.\n\n```js\nconst schema = Joi.any().meta({ index: true });\n```\n\n#### `any.note(...notes)`\n\nAnnotates the key where:\n- `notes` - the note string or multiple notes as individual arguments.\n\n```js\nconst schema = Joi.any().note('this is special', 'this is important');\n```\n\n#### `any.only()`\n\nRequires the validated value to match of the provided `any.allow()` values. It has no effect when\ncalled together with `any.valid()` since it already sets the requirements. When used with\n`any.allow()` it converts it to an `any.valid()`.\n\n#### `any.optional()`\n\nMarks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default.\n\nNote: this does not allow a `null` value. To do that, use [`any.allow(value)`](#anyallowvalue). Or both!\n\n```js\nconst schema = Joi.any().optional();\n```\n\n#### `any.prefs(options)` - aliases: `preferences`, `options`\n\nOverrides the global `validate()` options for the current key and any sub-key where:\n- `options` - an object with the same optional keys as [`any.validate()`](#anyvalidatevalue-options).\n\n```js\nconst schema = Joi.any().prefs({ convert: false });\n```\n\n#### `any.presence(mode)`\n\nSets the presence mode for the schema where:\n- `mode` - can be one of `'optional'`, `'required'`, or `'forbidden'`\n\nSame as calling `any.optional()`, `any.required()`, or `any.forbidden()`.\n\n#### `any.raw([enabled])`\n\nOutputs the original untouched value instead of the casted value where:\n- `enabled` - if `true`, the original result is returned, otherwise the validated value. Defaults to `true`.\n\nNote that the raw value is only applied after validation and any references to the value use the\nvalidated value, not the raw value.\n\n```js\nconst timestampSchema = Joi.date().timestamp();\ntimestampSchema.validate('12376834097810'); // { error: null, value: Sat Mar 17 2362 04:28:17 GMT-0500 (CDT) }\n\nconst rawTimestampSchema = Joi.date().timestamp().raw();\nrawTimestampSchema.validate('12376834097810'); // { error: null, value: '12376834097810' }\n```\n\n#### `any.required()` - aliases: `exist`\n\nMarks a key as required which will not allow `undefined` as value. All keys are optional by default.\n\n```js\nconst schema = Joi.any().required();\n```\n\nPossible validation errors: [`any.required`](#anyrequired)\n\n#### `any.result(mode)`\n\nSet the result mode where:\n- `mode` - one of `'raw'` (same as `any.raw()`) or `'strip'` (same as `any.strip()`).\n\n#### `any.rule(options)`\n\nApplies a set of rule options to the current ruleset or last rule added where:\n- `options` - the rules to apply where:\n  - `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`.\n  - `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.\n  - `warn` - if `true`, turns any error generated by the ruleset to warnings.\n\nWhen 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.\n\nRule 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.\n\n#### `any.ruleset` - aliases: `$`\n\nStarts a ruleset in order to apply multiple [rule options](#anyruleoptions). The set ends when\n[`rule()`](#anyruleoptions), [`keep()`](#anykeep), [`message()`](#anymessagemessage), or [`warn()`](#anywarn) is called.\n\n```js\nconst schema = Joi.number().ruleset.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n```js\nconst schema = Joi.number().$.min(1).max(10).rule({ message: 'Number must be between 1 and 10' });\n```\n\n#### `any.shared(schema)`\n\nRegisters a schema to be used by descendants of the current schema in named link references, where:\n- `schema` - a **joi** schema with an id.\n\n```js\n  const schema = Joi.object({\n      a: [Joi.string(), Joi.link('#x')],\n      b: Joi.link('#type.a')\n  })\n      .shared(Joi.number().id('x'))\n      .id('type');\n```\n\n#### `any.strict(isStrict)`\n\nStrict mode sets the `options.convert` options to `false` which prevent type casting for the current key and any child keys.\n- `isStrict` - whether strict mode is enabled or not. Defaults to true.\n\n```js\nconst schema = Joi.any().strict();\n```\n\n#### `any.strip([enabled])`\n\nMarks a key to be removed from a resulting object or array after validation to sanitize the output\nwhere:\n- `enabled` - if `true`, the value is stripped, otherwise the validated value is retained. Defaults\n  to `true`.\n\n```js\nconst schema = Joi.object({\n    username: Joi.string(),\n    password: Joi.string().strip()\n});\n\nschema.validate({ username: 'test', password: 'hunter2' }); // result.value = { username: 'test' }\n\nconst schema = Joi.array().items(Joi.string(), Joi.any().strip());\n\nschema.validate(['one', 'two', true, false, 1, 2]); // result.value = ['one', 'two']\n```\n\n#### `any.tag(...tags)`\n\nAnnotates the key where:\n- `tags` - the tag string or multiple tags (each as an argument).\n\n```js\nconst schema = Joi.any().tag('api', 'user');\n```\n\n#### `any.tailor(targets)`\n\nApplies any assigned target alterations to a copy of the schema that were applied via\n[`any.alter()`](#anyaltertargets) where:\n- `targets` - a single target string or array or target strings to apply.\n\n```js\nconst schema = Joi.object({\n    key: Joi.string()\n        .alter({\n            get: (schema) => schema.required(),\n            post: (schema) => schema.forbidden()\n        })  \n});\n\nconst getSchema = schema.tailor('get');\nconst postSchema = schema.tailor(['post']);\n```\n\n#### `any.unit(name)`\n\nAnnotates the key where:\n- `name` - the unit name of the value.\n\n```js\nconst schema = Joi.number().unit('milliseconds');\n```\n\n#### `any.valid(...values)` - aliases: `equal`\n\nAdds the provided values into the allowed values list and marks them as the only valid values allowed where:\n- `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.\n\n```js\nconst schema = {\n    a: Joi.any().valid('a'),\n    b: Joi.any().valid('b', 'B')\n};\n```\n\nPossible validation errors: [`any.only`](#anyonly)\n\n#### `any.validate(value, [options])`\n\nValidates a value using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object with the following optional keys:\n  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.\n  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.\n  - `cache` - when `true`, schema caching is enabled (for schemas with explicit caching rules). Default to `true`.\n  - `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()`.\n  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.\n  - `dateFormat` - sets the string format used when converting dates to strings in error messages and casting. Options are:\n    - `'date'` - date string.\n    - `'iso'` - date time ISO string. This is the default.\n    - `'string'` - JS default date time string.\n    - `'time'` - time string.\n    - `'utc'` - UTC date time string.\n  - `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`.\n  - `errors` - error formatting settings:\n    - `escapeHtml` - when `true`, error message templates will escape special characters to HTML entities, for security purposes. Defaults to `false`.\n    - `label` - defines the value used to set the `label` context variable:\n      - `'path'` - the full path to the value being validated. This is the default value.\n      - `'key'` - the key of the value being validated.\n      - `false` - remove any label prefix from error message, including the `\"\"`.\n    - `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')`);\n    - `render` - when `false`, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time. Defaults to `true`.\n    - `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).\n    - `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:\n        - `label` - the characters used around `{#label}` references. Defaults to `'\"'`.\n        - `array` - the characters used around array values. Defaults to `'[]'`.\n        - `string` - the characters used around each array string values. Defaults to `false`.\n    - `wrapArrays` - if `true`, array values in error messages are wrapped in `[]`. Defaults to `true`.\n  - `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`.\n  - `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`.\n  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.\n  - `nonEnumerables` - when `true`, inputs are shallow cloned to include non-enumerable properties. Defaults to `false`.\n  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`. Defaults to `'optional'`.\n  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.\n  - `stripUnknown` - remove unknown elements from objects and arrays. Defaults to `false`.\n    - when an `object` :\n      - `arrays` - set to `true` to remove unknown items from arrays.\n      - `objects` - set to `true` to remove unknown keys from objects.\n    - when `true`, it is equivalent to having `{ arrays: false, objects: true }`.\n\nReturns an object with the following keys:\n- `value` - the validated and normalized value.\n- `error` - the validation errors if found.\n- `warning` - the generated warnings if any.\n- `artifacts` - a `Map` containing any passing rules' artifacts and their corresponding array of paths.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\nconst result = schema.validate(value);\n// result -> { value: { \"a\" : 123 } }\n```\n\n#### `any.validateAsync(value, [options])`\n\nValidates a value asynchronously using the current schema and options where:\n- `value` - the value being validated.\n- `options` - an optional object as described in [`any.validate()`](#anyvalidatevalue-options), with the following additional settings:\n    - `artifacts` - when `true`, artifacts are returned alongside the value (i.e. `{ value, artifacts }`). Defaults to `false`.\n    - `warnings` - when `true`, warnings are returned alongside the value (i.e. `{ value, warning }`). Defaults to `false`.\n\nReturns 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.\n\n```js\nconst schema = Joi.object({\n    a: Joi.number()\n});\n\nconst value = {\n    a: '123'\n};\n\ntry {\n  const value = await schema.validateAsync(value);\n  // value -> { \"a\" : 123 }\n}\ncatch (err) {\n}\n```\n\n#### `any.warn()`\n\nSame as [`rule({ warn: true })`](#anyruleoptions).\n\nNote that `warn()` will terminate the current ruleset and cannot be followed by another rule option. Use [`rule()`](#anyruleoptions) to apply multiple rule options.\n\n#### `any.warning(code, [context])`\n\nGenerates a warning where:\n- `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.\n- `context` - optional context object.\n\nWhen 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).\n\n```js\nconst schema = Joi.any()\n    .warning('custom.x', { w: 'world' })\n    .message({ 'custom.x': 'hello {#w}!' });\n\nconst { value, error, warning } = schema.validate('anything');\n\n// value -> 'anything';\n// error -> null\n// warning -> { message: 'hello world!', details: [...] }\n\n// or\n\ntry {\n    const { value, warning } = await schema.validateAsync('anything', { warnings: true });\n    // value -> 'anything';\n    // warning -> { message: 'hello world!', details: [...] }\n}\ncatch (err) { }\n```\n\n#### `any['~standard']`\n\nProvides compatibility with the [Standard Schema](https://github.com/standard-schema/spec) specification. It contains a `jsonSchema` object with the following methods:\n\n- `input([options])` - returns the JSON\n</yakaai_skills>"}