Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Joi
https://joi.dev/
Admin
Joi is a powerful schema description language and data validator for JavaScript.
Tokens:
45,256
Snippets:
676
Trust Score:
8.9
Update:
1 month ago
Context
Chat
Benchmark
81.12
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Joi Source: https://joi.dev/ Installation commands for various package managers. ```console npm install joi ``` ```console yarn add joi ``` ```console pnpm add joi ``` -------------------------------- ### Install @hapi/pinpoint Source: https://joi.dev/module/pinpoint/api/3.x.x Installation commands for various package managers. ```console npm install @hapi/pinpoint@3.0.0 ``` ```console yarn add @hapi/pinpoint@3.0.0 ``` ```console pnpm add @hapi/pinpoint@3.0.0 ``` -------------------------------- ### any.example(example, [options]) Source: https://joi.dev/api/18.x.x Adds examples to the schema for documentation purposes. ```APIDOC ## any.example(example, [options]) ### Description Adds examples to the schema. No validation is performed on the example value. ### Parameters - **example** (any) - Required - The example value to add. - **options** (Object) - Optional - Settings for the example. - **override** (boolean) - Optional - If true, replaces any existing examples. Defaults to false. ``` -------------------------------- ### Install with yarn Source: https://joi.dev/module/address/install Use this command to install the package using yarn. ```bash yarn add @hapi/address@5.1.1 ``` -------------------------------- ### Install with npm Source: https://joi.dev/module/address/install Use this command to install the package using npm. ```bash npm install @hapi/address@5.1.1 ``` -------------------------------- ### Install with pnpm Source: https://joi.dev/module/address/install Use this command to install the package using pnpm. ```bash pnpm add @hapi/address@5.1.1 ``` -------------------------------- ### Install @hapi/formula Source: https://joi.dev/module/formula/install Use these commands to install the library via npm, yarn, or pnpm. ```console npm install @hapi/formula@4.0.0 ``` ```console yarn add @hapi/formula@4.0.0 ``` ```console pnpm add @hapi/formula@4.0.0 ``` -------------------------------- ### Install @hapi/formula Source: https://joi.dev/module/formula/api/3.x.x Installation commands for the @hapi/formula package using various package managers. ```console npm install @hapi/formula@3.0.2 ``` ```console yarn add @hapi/formula@3.0.2 ``` ```console pnpm add @hapi/formula@3.0.2 ``` -------------------------------- ### Add schema example Source: https://joi.dev/api/18.x.x Attaches an example value to the schema for documentation purposes. ```javascript const schema = Joi.string().min(4).example('abcd'); ``` -------------------------------- ### Install @hapi/tlds package Source: https://joi.dev/module/tlds/api/1.x.x Commands to install the package using various package managers. ```console npm install @hapi/tlds@1.1.7 ``` ```console yarn add @hapi/tlds@1.1.7 ``` ```console pnpm add @hapi/tlds@1.1.7 ``` -------------------------------- ### Install @joi/date via package managers Source: https://joi.dev/module/joi-date/install Commands to install version 3.0.0 of the @joi/date extension using common Node.js package managers. ```console npm install @joi/date@3.0.0 ``` ```console yarn add @joi/date@3.0.0 ``` ```console pnpm add @joi/date@3.0.0 ``` -------------------------------- ### Install @hapi/tlds via package managers Source: https://joi.dev/module/tlds/api/2.x.x Use these commands to install the @hapi/tlds package version 2.0.0 using npm, yarn, or pnpm. ```console npm install @hapi/tlds@2.0.0 ``` ```console yarn add @hapi/tlds@2.0.0 ``` ```console pnpm add @hapi/tlds@2.0.0 ``` -------------------------------- ### Use Ancestor Option for Relative Starting Points Source: https://joi.dev/api/18.x.x Demonstrates specifying the relative starting point using the ancestor integer option. ```javascript { x: { a: Joi.any(), b: { c: Joi.any(), d: Joi.ref('c', { ancestor: 1 }), e: Joi.ref('a', { ancestor: 2 }), f: Joi.ref('y', { ancestor: 3 }) } }, y: Joi.any() } ``` -------------------------------- ### Define a custom Joi schema extension Source: https://joi.dev/api/18.x.x Example of creating a schema using custom extension methods. ```javascript const schema = custom.object({ a: custom.million().round().dividable(Joi.ref('b')), b: custom.number(), c: custom.million().even().dividable(7), d: custom.million().round().prefs({ convert: false }), e: custom.million().large(), }); ``` -------------------------------- ### Implementing a Custom Cache Source: https://joi.dev/api/18.x.x Custom cache implementations must provide set and get methods to be compatible with any.cache(). ```javascript class { set(key, value) {} get(key) { return found ? value : undefined; } } ``` -------------------------------- ### Define and Validate Schema Source: https://joi.dev/api/18.x.x Example demonstrating complex object schema definition and both synchronous and asynchronous validation. ```javascript const Joi = require('joi'); const schema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required(), password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')), repeat_password: Joi.ref('password'), access_token: [Joi.string(), Joi.number()], birth_year: Joi.number().integer().min(1900).max(2013), email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] }, }), }) .with('username', 'birth_year') .xor('password', 'access_token') .with('password', 'repeat_password'); schema.validate({ username: 'abc', birth_year: 1994 }); // -> { value: { username: 'abc', birth_year: 1994 } } schema.validate({}); // -> { value: {}, error: '"username" is required' } // Also - try { const value = await schema.validateAsync({ username: 'abc', birth_year: 1994, }); } catch (err) {} ``` -------------------------------- ### string.guid() Source: https://joi.dev/api/18.x.x Requires the string value to be a valid GUID. Supports version, separator, and wrapper options. ```APIDOC ## string.guid() ### Description Requires the string value to be a valid GUID. ### Parameters - **options** (object) - Optional settings: - **version** (Array|String) - Specifies acceptable versions (uuidv1-uuidv8). - **separator** (boolean|string) - Defines allowed or required GUID separator. - **wrapper** (boolean|string) - Defines allowed or required GUID wrapper characters. ### Request Example ```javascript const schema = Joi.string().guid({ version: ['uuidv4', 'uuidv5'], wrapper: false, }); ``` ``` -------------------------------- ### Validate GUID strings with Joi Source: https://joi.dev/api/18.x.x Configures a schema to validate GUIDs with specific version requirements and wrapper constraints. ```javascript const schema = Joi.string().guid({ version: ['uuidv4', 'uuidv5'], wrapper: false, }); ``` -------------------------------- ### any.type Source: https://joi.dev/api/18.x.x Gets the type of the schema. ```APIDOC ## any.type ### Description Gets the type of the schema. ``` -------------------------------- ### Create Joi References Source: https://joi.dev/api/18.x.x Demonstrates basic usage of Joi.ref() to point to sibling keys and context variables. ```javascript const schema = Joi.object({ a: Joi.ref('b.c'), b: { c: Joi.any(), }, c: Joi.ref('$x'), }); await schema.validateAsync({ a: 5, b: { c: 5 } }, { context: { x: 5 } }); ``` -------------------------------- ### Basic Usage Source: https://joi.dev/module/joi-date/api/3.x.x Initialize the Joi extension and define a date schema with a specific format. ```js import BaseJoi from 'joi'; import { JoiDate } from '@joi/date'; const Joi = BaseJoi.extend(JoiDate); const schema = Joi.date().format('YYYY-MM-DD'); ``` -------------------------------- ### Basic Usage Source: https://joi.dev/module/joi-date/api/2.x.x Demonstrates how to extend Joi with the date module and define a basic date schema with a specific format and UTC setting. ```APIDOC ## Basic Usage ### Description Extend Joi with the date module and define a schema for dates. ### Method ```javascript const Joi = require('joi').extend(require('@joi/date')); const schema = Joi.date().format('YYYY-MM-DD').utc(); ``` ``` -------------------------------- ### link.ref(ref) Source: https://joi.dev/api/18.x.x Initializes the schema after construction for cases where the schema has to be constructed first and then initialized. ```APIDOC ## link.ref(ref) ### Description Initializes the link reference if it was not provided during the initial Joi.link() call. Must be called prior to validation if the link was not initialized. ``` -------------------------------- ### Applying rulesets Source: https://joi.dev/api/18.x.x Demonstrates applying multiple rule options to a schema using ruleset or the $ alias. ```javascript const schema = Joi.number() .ruleset.min(1) .max(10) .rule({ message: 'Number must be between 1 and 10' }); ``` ```javascript const schema = Joi.number() .$.min(1) .max(10) .rule({ message: 'Number must be between 1 and 10' }); ``` -------------------------------- ### Evaluate a Formula Source: https://joi.dev/module/formula/api/3.x.x Demonstrates initializing a Formula parser with custom functions, constants, and a reference resolver, followed by evaluation against a context object. ```javascript const Formula = require('@hapi/formula'); const functions = { x: (value) => value + 10, }; const constants = { Z: 100, }; const reference = function (name) { return (context) => context[name]; }; const formula = new Formula.Parser('1 + a.b.c.2.4.x + [b] + x([y + 4] + Z)', { functions, constants, reference, }); formula.evaluate({ 'a.b.c.2.4.x': 2, b: 3, 'y + 4': 5 }); // 1 + 2 + 3 + 5 + 10 + 100 formula.evaluate({ 'a.b.c.2.4.x': '2', b: 3, 'y + 4': '5' }); // '123510010' ``` -------------------------------- ### Get caller location with `location(depth)` Source: https://joi.dev/module/pinpoint/api/2.x.x The `location(depth)` function returns the filename and line number of the caller in the call stack. The `depth` parameter specifies the distance from the `location()` function. Defaults to 1 (the immediate caller). ```javascript const pinpoint = require('@hapi/pinpoint'); const callerInfo = pinpoint.location(1); // callerInfo will be an object like { filename: '...', line: ... } ``` -------------------------------- ### any.describe() Source: https://joi.dev/api/18.x.x Returns an object that represents the internal configuration of the schema. ```APIDOC ## any.describe() ### Description Returns an object that represents the internal configuration of the schema. Useful for debugging and exposing a schema's configuration to other systems. ``` -------------------------------- ### Initialize a link reference after construction Source: https://joi.dev/api/18.x.x Use link.ref() when the schema must be constructed before the reference is known. ```javascript const schema = Joi.object({ a: [Joi.string(), Joi.number()], b: Joi.link().ref('#type.a'), }).id('type'); ``` -------------------------------- ### object.instance(constructor, [name]) Source: https://joi.dev/api/18.x.x Requires the object to be an instance of a given constructor. ```APIDOC ## object.instance(constructor, [name]) ### Description Requires the object to be an instance of a given constructor function. ### Parameters - **constructor** (function) - Required - The constructor function the object must be an instance of. - **name** (string) - Optional - An alternate name to use in validation errors. ``` -------------------------------- ### Set default values with any.default Source: https://joi.dev/api/18.x.x Demonstrates using literal values, functions, and dynamic generators for default schema values. ```javascript const generateUsername = (parent, helpers) => { return parent.firstname.toLowerCase() + '-' + parent.lastname.toLowerCase(); }; generateUsername.description = 'generated username'; const schema = Joi.object({ username: Joi.string().default(generateUsername), firstname: Joi.string(), lastname: Joi.string(), created: Joi.date().default(Date.now), status: Joi.string().default('registered'), }); const { value } = schema.validate({ firstname: 'Jane', lastname: 'Doe', }); // value.status === 'registered' // value.username === 'jane-doe' // value.created will be the time of validation ``` -------------------------------- ### object.with(key, peers, [options]) Source: https://joi.dev/api/18.x.x Requires the presence of other keys whenever the specified key is present. ```APIDOC ## object.with(key, peers, [options]) ### Description Requires the presence of other keys whenever the specified key is present. ### Parameters - **key** (string) - Required - The reference key. - **peers** (string|array) - Required - The required peer key names. - **options** (object) - Optional - Configuration object: - **separator** (string|boolean) - Optional - Overrides the default hierarchy separator. - **isPresent** (function) - Optional - Function that overrides the default check for an empty value. ``` -------------------------------- ### any.meta(meta) Source: https://joi.dev/api/18.x.x Attaches metadata to the key. ```APIDOC ## any.meta(meta) ### Description Attaches metadata to the key. ### Parameters - **meta** (object) - Required - The meta object to attach. ``` -------------------------------- ### compile(schema, [options]) Source: https://joi.dev/api/18.x.x Converts a literal schema definition to a Joi schema object. ```APIDOC ## compile(schema, [options]) ### Description Converts literal schema definition to joi schema object. ### Parameters - **schema** (any) - Required - The schema definition to compile. - **options** (object) - Optional - Settings object. - **legacy** (boolean) - Optional - If true, returns a schema compatible with older versions of Joi. ``` -------------------------------- ### cache.provision([options]) Source: https://joi.dev/api/18.x.x Provisions a simple LRU cache for caching simple inputs. ```APIDOC ## cache.provision([options]) ### Description Provisions a simple LRU cache for caching simple inputs (undefined, null, strings, numbers, and booleans). ### Parameters - **options** (object) - Optional - Settings object. - **max** (number) - Optional - Number of items to store before dropping least used items (Defaults to 1000). ``` -------------------------------- ### any.description(desc) Source: https://joi.dev/api/18.x.x Annotates the key with a description string. ```APIDOC ## any.description(desc) ### Description Annotates the key with a description string. ### Parameters - **desc** (string) - Required - The description string. ``` -------------------------------- ### Inspect schema configuration with any.describe Source: https://joi.dev/api/18.x.x Retrieves the internal configuration object of a schema for debugging or UI integration. ```javascript const schema = Joi.any().valid('foo', 'bar'); console.log(schema.describe()); ``` ```text { type: 'any', flags: { only: true }, valids: [ 'foo', 'bar' ] } ``` -------------------------------- ### any.note(...notes) Source: https://joi.dev/api/18.x.x Annotates the key. ```APIDOC ## any.note(...notes) ### Description Annotates the key. ### Parameters - **notes** (string) - Required - The note string or multiple notes as individual arguments. ``` -------------------------------- ### Create custom Joi instance with Joi.defaults Source: https://joi.dev/api/18.x.x Creates a new Joi instance that applies a modifier function to every new schema created. ```javascript const custom = Joi.defaults((schema) => { switch (schema.type) { case 'string': return schema.allow(''); case 'object': return schema.min(1); default: return schema; } }); const schema = custom.object(); // Returns Joi.object().min(1) ``` -------------------------------- ### Joi.version Source: https://joi.dev/api/18.x.x Property showing the current version of joi being used. ```APIDOC ## Joi.version ### Description Property showing the current version of joi being used. ``` -------------------------------- ### Annotate keys with any.description Source: https://joi.dev/api/18.x.x Adds a description string to a schema key for documentation purposes. ```javascript const schema = Joi.any().description( 'this key will match anything you give it', ); ``` -------------------------------- ### string.ipVersion error context Source: https://joi.dev/api/18.x.x Provides the CIDR and the list of accepted IP versions. ```typescript { cidr: string, // CIDR used for the validation version: Array<string> // List of IP version accepted } ``` -------------------------------- ### Compile schema definitions with Joi.compile Source: https://joi.dev/api/18.x.x Converts literal schema definitions into Joi schema objects. ```javascript const definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }]; const schema = Joi.compile(definition); // Same as: const schema = Joi.alternatives().try( Joi.string().valid('key'), Joi.number().valid(5), Joi.object({ a: Joi.boolean().valid(true), b: Joi.alternatives().try( Joi.string().pattern(/^a/), Joi.string().valid('boom'), ), }), ); ``` -------------------------------- ### Absolute Path Reference Source: https://joi.dev/api/18.x.x Use the '/' prefix to specify an absolute path from the value root in a Joi reference. ```javascript { x: { a: Joi.any(), b: { c: Joi.ref('/x.a') } } } ``` -------------------------------- ### object.and(...peers, [options]) Source: https://joi.dev/api/18.x.x Defines an all-or-nothing relationship between keys. ```APIDOC ## object.and(...peers, [options]) ### Description Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required. ### Parameters - **peers** (string[]) - Required - The key names that must all be present if one is present. - **options** (object) - Optional - Configuration settings including 'separator' and 'isPresent' override function. ``` -------------------------------- ### Use Separator Prefixes for Ancestor References Source: https://joi.dev/api/18.x.x Illustrates using dot-based prefixes to navigate up the object hierarchy for references. ```javascript { x: { a: Joi.any(), b: { c: Joi.any(), d: Joi.ref('c'), e: Joi.ref('...a'), f: Joi.ref('....y') } }, y: Joi.any() } ``` -------------------------------- ### in(ref, [options]) Source: https://joi.dev/api/18.x.x Creates a reference used as an array of values to match against a rule. ```APIDOC ## in(ref, [options]) ### Description Creates a reference that, when resolved, is used as an array of values to match against the rule. Can only be used in rules that support in-references. ``` -------------------------------- ### Joi.alternatives() Source: https://joi.dev/api/18.x.x Generates a type that matches one of the provided alternative schemas. If no schemas are provided, it only matches undefined. ```APIDOC ## Joi.alternatives() ### Description Generates a type that will match one of the provided alternative schemas via the try() method. Alternatives can also be expressed using the shorter [] notation. ### Usage ```javascript const alt = Joi.alternatives().try(Joi.number(), Joi.string()); // Same as [Joi.number(), Joi.string()] ``` ``` -------------------------------- ### extend(...extensions) Source: https://joi.dev/api/18.x.x Creates a new customized instance of the Joi module without modifying the original. ```APIDOC ## extend(...extensions) ### Description Creates a new customized instance of the joi module using the provided extension configurations. ``` -------------------------------- ### Construct Schema Source: https://joi.dev/api/18.x.x Basic schema construction. Note that Joi schemas are immutable. ```javascript const schema = Joi.object({ a: Joi.string(), }); ``` -------------------------------- ### Implement Note Comments Source: https://joi.dev/policies/styleguide Use notes to explain specific statement behavior, placed immediately at the end of the statement. ```javascript function execute(value) { if (value !== null && value !== undefined) { // Explicit check as 'value' can be 0 console.log(value); } } ``` -------------------------------- ### Basic Usage of @joi/date Source: https://joi.dev/module/joi-date/api/2.x.x Extends Joi with date validation and sets a specific date format and UTC parsing. ```javascript const Joi = require('joi').extend(require('@joi/date')); const schema = Joi.date().format('YYYY-MM-DD').utc(); ``` -------------------------------- ### Define alternatives.all error context Source: https://joi.dev/api/18.x.x Context properties for the alternatives.all error type. ```typescript { details: Array<object>, // An array of details for each error found while trying to match to each of the alternatives message: string // The combined error messages } ``` -------------------------------- ### string.uri([options]) Source: https://joi.dev/api/18.x.x Requires the string value to be a valid RFC 3986 URI. ```APIDOC ## string.uri([options]) ### Description Requires the string value to be a valid RFC 3986 URI. ### Parameters - **options** (object) - Optional - Settings for URI validation including scheme, allowRelative, relativeOnly, allowQuerySquareBrackets, domain, and encodeUri. ``` -------------------------------- ### Using Joi.types() Source: https://joi.dev/api/18.x.x Returns an object containing plain Joi schema types for creating shortcuts via deconstruction. ```javascript const Joi = require('joi'); const { object, string } = Joi.types(); const schema = object.keys({ property: string.min(4), }); ``` -------------------------------- ### Create Schema Variants with .alter() and .tailor() Source: https://joi.dev/ Use .alter() to define context-specific rules and .tailor() to generate the variant schema. ```js const schema = Joi.object({ id: Joi.number().alter({ create: (s) => s.forbidden(), update: (s) => s.required(), }), name: Joi.string().required(), }); const createSchema = schema.tailor('create'); const updateSchema = schema.tailor('update'); ``` -------------------------------- ### any.fork(paths, adjuster) Source: https://joi.dev/api/18.x.x Returns a new schema where each of the path keys listed have been modified. ```APIDOC ## any.fork(paths, adjuster) ### Description Returns a new schema where each of the path keys listed have been modified. The method does not modify the original schema. ### Parameters - **paths** (array|string) - Required - An array of key strings, a single key string, or an array of arrays of pre-split key strings. - **adjuster** (function) - Required - A function using the signature function(schema) which must return a modified schema. ``` -------------------------------- ### any['~standard'] Source: https://joi.dev/api/18.x.x Provides compatibility with the Standard Schema specification via a jsonSchema object. ```APIDOC ## any['~standard'] ### Description Provides compatibility with the Standard Schema specification. Contains a jsonSchema object with methods to retrieve schema definitions. ### Methods - **input([options])** - Returns the JSON Schema for the input value. - **output([options])** - Returns the JSON Schema for the output value. ### Options - **target** (string) - Optional - The JSON Schema target version (defaults to 'draft-2020-12'). ``` -------------------------------- ### Validating with Joi.any() Source: https://joi.dev/api/18.x.x Creates a schema that matches any data type. ```javascript const any = Joi.any(); await any.validateAsync('a'); ``` -------------------------------- ### string.base64([options]) Source: https://joi.dev/api/18.x.x Requires the string value to be a valid base64 string. ```APIDOC ## string.base64([options]) ### Description Requires the string value to be a valid base64 string; does not check the decoded value. ### Parameters - **options** (object) - Optional - Settings including `paddingRequired` (boolean) and `urlSafe` (boolean). ``` -------------------------------- ### Joi.any() Source: https://joi.dev/api/18.x.x Generates a schema object that matches any data type. ```APIDOC ## Joi.any() ### Description Generates a schema object that matches any data type. ``` -------------------------------- ### Non-String Input Behavior Source: https://joi.dev/module/joi-date/api/3.x.x Demonstrates how format() only applies to string inputs, while other types fall back to default Joi date coercion. ```js const schema = Joi.date().format('YYYYMMDD'); schema.validate('20211029'); // 2021-10-29 schema.validate(20211029); // 1970-01-01T05:36:51.029Z ``` -------------------------------- ### General Newline Structure Source: https://joi.dev/policies/styleguide Demonstrates basic function and utility structure with required newlines. ```javascript exports.get = function () { // Some code }; // 1 // 2 /** * jsDoc comment */ internals.utility = function () { //Some code }; ``` -------------------------------- ### Define a recursive schema using named links Source: https://joi.dev/api/18.x.x Uses .id() to name a schema and Joi.link() to reference it by that name. ```javascript const person = Joi.object({ firstName: Joi.string().required(), lastName: Joi.string().required(), children: Joi.array().items(Joi.link('#person')), }).id('person'); ``` -------------------------------- ### any.optional() Source: https://joi.dev/api/18.x.x Marks a key as optional, allowing undefined values. This is the default behavior for all keys. ```APIDOC ## any.optional() ### Description Marks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default. ### Usage ```javascript const schema = Joi.any().optional(); ``` ``` -------------------------------- ### new Formula.Parser(formula, [options]) Source: https://joi.dev/module/formula/api/3.x.x Creates a new formula parser instance with the specified formula string and optional configuration for constants, token validation, variable resolution, and functions. ```APIDOC ## new Formula.Parser(formula, [options]) ### Description Creates a new formula parser object. ### Parameters - **formula** (string) - Required - The formula string to parse. - **options** (object) - Optional - Configuration settings: - **constants** (object) - A hash of key-value pairs used to convert constants to values. - **tokenRx** (RegExp) - A regular expression used to validate token variables. - **reference** (function) - A variable resolver factory function with signature `function(variable)` which returns a function with signature `function(context)` returning the resolved `variable`. - **functions** (object) - A hash of key-value pairs used to resolve formula functions. ``` -------------------------------- ### any.unit(name) Source: https://joi.dev/api/18.x.x Annotates the key with a unit name. ```APIDOC ## any.unit(name) ### Description Annotates the key with a unit name. ### Parameters - **name** (string) - Required - The unit name of the value. ``` -------------------------------- ### Require peer keys with with() Source: https://joi.dev/api/18.x.x Ensures that if the specified key is present, the listed peer keys must also be present. ```javascript const schema = Joi.object({ a: Joi.any(), b: Joi.any(), }).with('a', 'b'); ``` -------------------------------- ### Joi.extend() Source: https://joi.dev/api/18.x.x Extends the Joi library with a custom schema type definition. ```APIDOC ## Joi.extend(extension) ### Description Creates a new Joi instance with custom types and rules defined by the provided extension object. ### Parameters - **extension** (function) - Required - A function that receives the base Joi instance and returns an object defining the new type, base, messages, coercion logic, validation rules, and overrides. ``` -------------------------------- ### Object Inline and Newline Rules Source: https://joi.dev/policies/styleguide Illustrates correct versus incorrect usage of inline objects and newline placement after braces. ```javascript // Right if (condition) { execute(value, { strict: true }); } if (condition) { const options = { strict: true, }; execute(value, options); } const empty = {}; // Wrong if (condition) { execute(value, { strict: true }); } if (condition) { const options = { strict: true }; execute(value, options); } const empty = {}; ``` -------------------------------- ### binary.min(limit) Source: https://joi.dev/api/18.x.x Specifies the minimum length of the buffer. ```APIDOC ## binary.min(limit) ### Description Specifies the minimum length of the buffer. ### Parameters - **limit** (number|reference) - Required - The lowest size of the buffer allowed. ``` -------------------------------- ### string.case(direction) Source: https://joi.dev/api/18.x.x Sets the required string case. ```APIDOC ## string.case(direction) ### Description Sets the required string case. ### Parameters - **direction** (string) - Required - Can be either 'upper' or 'lower'. ``` -------------------------------- ### Conditional Requirement Using any.when Source: https://joi.dev/api/18.x.x The correct approach to enforce a required rule based on a condition. ```javascript const schema = { a: Joi.when('b', { is: true, then: Joi.required() }), b: Joi.boolean(), }; ``` -------------------------------- ### object.or(...peers, [options]) Source: https://joi.dev/api/18.x.x Defines a relationship where at least one of the specified keys is required. ```APIDOC ## object.or(...peers, [options]) ### Description Defines a relationship between keys where one of the peers is required. ### Parameters - **peers** (string) - Required - The key names of which at least one must appear. - **options** (object) - Optional - Settings including 'separator' and 'isPresent' function. ``` -------------------------------- ### binary.min context Source: https://joi.dev/api/18.x.x Context for falling below minimum buffer length. ```typescript { limit: number; // Minimum length that was expected for this buffer } ``` -------------------------------- ### Annotating with notes Source: https://joi.dev/api/18.x.x Adds descriptive notes to a schema key. ```javascript const schema = Joi.any().note('this is special', 'this is important'); ``` -------------------------------- ### Structure Node.js Modules Source: https://joi.dev/policies/styleguide Use uppercase for imported modules and define all globals within the 'internals' object. Execute module logic within an init function. ```javascript // Right const Hapi = require('hapi'); const Hoek = require('hoek'); const Package = require('./package.json'); const internals = { foo: 'bar' }; internals.init = function () { const server = new Hapi.Server(); ... }; internals.init(); // Also right const Hapi = require('hapi'); const internals = {}; internals.package = require('./package.json'); internals.foo = 'bar'; internals.init = function () { const server = new Hapi.server(); ... }; internals.init(); // Wrong const hapi = require('hapi'); // Use uppercase name const foo = 'bar'; // No global vars outside of internals const internals = { Foo: 'bar' // Don't use uppercase vars inside internals }; const server = new Hapi.Server(); // No global vars outside of internals and exports / Set up your module inside an init() function ... const Hoek = require('hoek'); // Declare modules at the top of the module ``` -------------------------------- ### object.min(limit) Source: https://joi.dev/api/18.x.x Specifies the minimum number of keys allowed in the object. ```APIDOC ## object.min(limit) ### Description Specifies the minimum number of keys in the object. ### Parameters - **limit** (number|reference) - Required - The lowest number of keys allowed. ``` -------------------------------- ### Generating and Retrieving Warnings Source: https://joi.dev/api/18.x.x Demonstrates how to define a custom warning and retrieve it during both synchronous and asynchronous validation. ```javascript const schema = Joi.any() .warning('custom.x', { w: 'world' }) .message({ 'custom.x': 'hello {#w}!' }); const { value, error, warning } = schema.validate('anything'); // value -> 'anything'; // error -> null // warning -> { message: 'hello world!', details: [...] } // or try { const { value, warning } = await schema.validateAsync('anything', { warnings: true, }); // value -> 'anything'; // warning -> { message: 'hello world!', details: [...] } } catch (err) {} ``` -------------------------------- ### any.tag(...tags) Source: https://joi.dev/api/18.x.x Annotates the key with one or more tag strings. ```APIDOC ## any.tag(...tags) ### Description Annotates the key with one or more tag strings. ### Parameters - **tags** (string) - Required - The tag string or multiple tags (each as an argument). ``` -------------------------------- ### Validate and return with Joi.attempt Source: https://joi.dev/api/18.x.x Validates a value against a schema, returning the valid object or throwing an error on failure. ```javascript Joi.attempt('x', Joi.number()); // throws error const result = Joi.attempt('4', Joi.number()); // result -> 4 ``` -------------------------------- ### Attempting Alternative Matches Source: https://joi.dev/api/18.x.x Defines multiple potential schemas for a value to match against. ```javascript const alt = Joi.alternatives().try(Joi.number(), Joi.string()); await alt.validateAsync('a'); ``` -------------------------------- ### object.schema([type]) Source: https://joi.dev/api/18.x.x Requires the object to be a joi schema instance. ```APIDOC ## object.schema([type]) ### Description Requires the object to be a joi schema instance. ### Parameters - **type** (joi schema) - Optional - The specific joi schema to require. ``` -------------------------------- ### alternatives.try(...schemas) Source: https://joi.dev/api/18.x.x Adds an alternative schema type for attempting to match against the validated value. ```APIDOC ## alternatives.try(...schemas) ### Description Adds an alternative schema type for attempting to match against the validated value. ### Parameters - **schemas** (...schema) - Required - Alternative joi types to attempt to match. ``` -------------------------------- ### Define OR key relationship Source: https://joi.dev/api/18.x.x Requires at least one of the specified peer keys to be present. ```javascript const schema = Joi.object({ a: Joi.any(), b: Joi.any(), }).or('a', 'b'); ``` -------------------------------- ### Joi.ref(key, [options]) Source: https://joi.dev/api/18.x.x Generates a reference to the value of the named key. References are resolved at validation time and support sibling, ancestor, and context lookups. ```APIDOC ## Joi.ref(key, [options]) ### Description Generates a reference to the value of the named key. References are resolved at validation time and in order of dependency. ### Parameters - **key** (string) - Required - The reference target. Can point to sibling keys, ancestor keys (using `...` prefix), or context references (using `$` prefix). - **options** (object) - Optional - Configuration settings: - **adjust** (function) - A function to transform the resolved reference value. - **map** (array) - An array of array pairs to map the resolved value to another value. - **prefix** (object) - Overrides for default prefix characters (global, local, root). - **separator** (string/boolean) - Overrides the default hierarchy separator. - **ancestor** (number) - Sets the reference relative starting point. - **in** (any) - Creates an in-reference. - **iterables** (boolean) - If true, resolves by reaching into maps and sets. - **render** (boolean) - If true, uses the reference value instead of its name in error messages. ``` -------------------------------- ### string.domain([options]) Source: https://joi.dev/api/18.x.x Requires the string value to be a valid domain name. ```APIDOC ## string.domain([options]) ### Description Requires the string value to be a valid domain name. ### Parameters - **options** (object) - Optional settings: - **allowFullyQualified** (boolean) - Optional - If true, domains ending with a '.' character are permitted. Defaults to false. - **allowUnicode** (boolean) - Optional - If true, Unicode characters are permitted. Defaults to true. - **allowUnderscore** (boolean) - Optional - If true, underscores ('_') are allowed in the domain name. Defaults to false. - **minDomainSegments** (number) - Optional - Number of segments required for the domain. Defaults to 2. - **maxDomainSegments** (number) - Optional - Maximum number of allowed domain segments. Default to no limit. - **tlds** (object) - Optional - Options for TLD validation. Supports 'allow' (Set/array/boolean) or 'deny' (Set/array). ### Example ```javascript const schema = Joi.string().domain(); ``` ``` -------------------------------- ### date.min(date) Source: https://joi.dev/api/18.x.x Specifies the oldest date allowed. Accepts a date string, 'now', or a Joi reference. ```APIDOC ## date.min(date) ### Description Specifies the oldest date allowed for a date schema. ### Parameters - **date** (string|reference) - Required - The oldest date allowed, a reference, or 'now'. ``` -------------------------------- ### any['~standard'] Source: https://joi.dev/api/18.x.x Exports the schema to a standard JSON schema representation. ```APIDOC ## any['~standard'] ### Description Returns the schema representation in a standard format, such as JSON schema. ### Usage ```javascript const schema = Joi.string().min(5); const jsonSchema = schema['~standard'].jsonSchema.input(); ``` ``` -------------------------------- ### checkPreferences(prefs) Source: https://joi.dev/api/18.x.x Checks if the provided preferences are valid. ```APIDOC ## checkPreferences(prefs) ### Description Checks if the provided preferences are valid. Throws an exception if the prefs object is invalid. ### Parameters - **prefs** (object) - Required - The preferences object to validate. ``` -------------------------------- ### string.pattern(regex, [name | options]) Source: https://joi.dev/api/18.x.x Defines a pattern rule using a regular expression. ```APIDOC ## string.pattern(regex, [name | options]) ### Description Defines a pattern rule where the string value must match the provided regular expression. ``` -------------------------------- ### Configure default value for empty strings Source: https://joi.dev/api/18.x.x Sets a default value when an empty string is provided, as empty strings are disallowed by default in Joi. ```javascript Joi.string().empty('').default('default value'); ``` -------------------------------- ### string.length(limit, [encoding]) Source: https://joi.dev/api/18.x.x Specifies the exact string length required. ```APIDOC ## string.length(limit, [encoding]) ### Description Specifies the exact string length required. If encoding is provided, length is calculated in bytes. ### Parameters - **limit** (number|reference) - Required - The required string length. - **encoding** (string) - Optional - Encoding used to calculate byte length. ``` -------------------------------- ### binary.length(limit) Source: https://joi.dev/api/18.x.x Specifies the exact length of the buffer. ```APIDOC ## binary.length(limit) ### Description Specifies the exact length of the buffer. ### Parameters - **limit** (number|reference) - Required - The size of buffer allowed. ``` -------------------------------- ### alternatives.match(mode) Source: https://joi.dev/api/18.x.x Requires the validated value to match a specific set of the provided alternative.try() schemas. ```APIDOC ## alternatives.match(mode) ### Description Requires the validated value to match a specific set of the provided `alternative.try()` schemas. ### Parameters - **mode** (string) - Required - The match mode: 'any' (default), 'all', or 'one'. ``` -------------------------------- ### string.dataUri([options]) Source: https://joi.dev/api/18.x.x Requires the string value to be a valid data URI string. ```APIDOC ## string.dataUri([options]) ### Description Requires the string value to be a valid data URI string. ### Parameters - **options** (object) - Optional - Settings including `paddingRequired` (boolean). ``` -------------------------------- ### any.allow(...values) Source: https://joi.dev/api/18.x.x Allows specific values in addition to any other permitted values. ```APIDOC ## any.allow(...values) ### Description Allows values which will be matched against the validated value before applying any other rules. Supports references and in-references. ``` -------------------------------- ### Enable Strict Mode in JavaScript Source: https://joi.dev/policies/styleguide The first line of every file should be 'use strict';. If a shebang is present, it should be on the second line, followed by a blank line. ```javascript // Right 'use strict'; console.log('even when not required'); // Also right #!/usr/bin/env node 'use strict'; console.log('even when not required'); // Wrong 'use strict'; console.log('even when not required') ``` -------------------------------- ### string.min(limit, [encoding]) Source: https://joi.dev/api/18.x.x Specifies the minimum number of string characters. ```APIDOC ## string.min(limit, [encoding]) ### Description Specifies the minimum number of string characters required. ``` -------------------------------- ### Object and Function Spacing Source: https://joi.dev/policies/styleguide Use spaces inside braces for inlined objects, but keep empty objects compact. Empty functions should contain a single space. ```javascript // Right execute({ name: 'john', email: 'john@example.com' }); const empty = {}; const callback = () => {}; // Wrong execute({ name: 'john', email: 'john@example.com' }); const empty = {}; const callback = () => {}; ``` -------------------------------- ### attempt(value, schema, [message], [options]) Source: https://joi.dev/api/18.x.x Validates a value against a schema, returns the valid object, and throws if validation fails. ```APIDOC ## attempt(value, schema, [message], [options]) ### Description Validates a value against a schema, returns the valid object, and throws if validation fails. ### Parameters - **value** (any) - Required - The value to validate. - **schema** (object) - Required - The validation schema. - **message** (string/Error) - Optional - Message string prefix or Error object. - **options** (object) - Optional - Options passed to any.validate. ``` -------------------------------- ### new Formula.Parser(formula, [options]) Source: https://joi.dev/module/formula/api/4.x.x Creates a new formula parser instance to process a specific formula string with optional configuration for constants, token validation, variable resolution, and custom functions. ```APIDOC ## new Formula.Parser(formula, [options]) ### Description Creates a new formula parser object. ### Parameters - **formula** (string) - Required - The formula string to parse. - **options** (object) - Optional - Settings for the parser: - **constants** (object) - A hash of key-value pairs used to convert constants to values. - **tokenRx** (RegExp) - A regular expression used to validate token variables. - **reference** (function) - A variable resolver factory function with signature `function(variable)` which returns a function with signature `function(context)` returning the resolved `variable`. - **functions** (object) - A hash of key-value pairs used to resolve formula functions. ``` -------------------------------- ### Set binary length constraints Source: https://joi.dev/api/18.x.x Defines exact, minimum, or maximum length requirements for the buffer. ```javascript const schema = Joi.binary().length(5); ``` ```javascript const schema = Joi.binary().max(10); ``` ```javascript const schema = Joi.binary().min(2); ``` -------------------------------- ### Joi.types() Source: https://joi.dev/api/18.x.x Returns an object where each key is a plain joi schema type, useful for creating type shortcuts. ```APIDOC ## Joi.types() ### Description Returns an object where each key is a plain joi schema type. Useful for creating type shortcuts using deconstruction. Note that the types are already formed and do not need to be called as functions. ``` -------------------------------- ### object.keys([schema]) Source: https://joi.dev/api/18.x.x Sets or extends the allowed object keys. ```APIDOC ## object.keys([schema]) ### Description Sets or extends the allowed object keys. If schema is empty, no keys are allowed; if null/undefined, any key is allowed. ### Parameters - **schema** (object) - Optional - An object where each key is assigned a Joi type. ``` -------------------------------- ### defaults(modifier) Source: https://joi.dev/api/18.x.x Creates a new Joi instance that applies a modifier function to every new schema. ```APIDOC ## defaults(modifier) ### Description Creates a new joi instance that applies the provided modifier function to every new schema. ### Parameters - **modifier** (function) - Required - A function with signature function(schema) that must return a schema object. ``` -------------------------------- ### any.prefs(options) Source: https://joi.dev/api/18.x.x Overrides the global validate() options for the current key and any sub-key. ```APIDOC ## any.prefs(options) ### Description Overrides the global `validate()` options for the current key and any sub-key. ### Parameters - **options** (object) - Required - An object with the same optional keys as `any.validate()`. ### Usage ```javascript const schema = Joi.any().prefs({ convert: false }); ``` ``` -------------------------------- ### Create an in-reference validation Source: https://joi.dev/api/18.x.x Use Joi.in to match a value against an array defined by another key in the schema. ```javascript const schema = Joi.object({ a: Joi.array().items(Joi.number()), b: Joi.number().valid(Joi.in('a')), }); ``` -------------------------------- ### string.creditCard() Source: https://joi.dev/api/18.x.x Requires the number to be a credit card number (Using Luhn Algorithm). ```APIDOC ## string.creditCard() ### Description Requires the number to be a credit card number (Using Luhn Algorithm). ``` -------------------------------- ### Joi.link(ref) Source: https://joi.dev/api/18.x.x Links to another schema node and reuses it for validation, typically for recursive schemas. ```APIDOC ## Joi.link(ref) ### Description Links to another schema node and reuses it for validation. Supports relative, absolute, and named references. ### Parameters - **ref** (string) - Required - The reference to the linked schema node. ``` -------------------------------- ### object.nand(...peers, [options]) Source: https://joi.dev/api/18.x.x Defines a relationship where not all specified keys can be present at the same time. ```APIDOC ## object.nand(...peers, [options]) ### Description Defines a relationship between keys where not all peers can be present at the same time. ### Parameters - **peers** (string) - Required - The key names of which if one is present, the others may not all be present. - **options** (object) - Optional - Settings including 'separator' and 'isPresent' function. ``` -------------------------------- ### any.required() Source: https://joi.dev/api/18.x.x Marks a key as required, disallowing undefined values. ```APIDOC ## any.required() ### Description Marks a key as required which will not allow `undefined` as value. ### Usage ```javascript const schema = Joi.any().required(); ``` ``` -------------------------------- ### Validate hostname strings with Joi Source: https://joi.dev/api/18.x.x Ensures the string conforms to RFC1123 hostname requirements. ```javascript const schema = Joi.string().hostname(); ``` -------------------------------- ### string.min error context Source: https://joi.dev/api/18.x.x Provides the minimum expected length and optional encoding. ```typescript { limit: number, // Minimum length that was expected for this string encoding: undefined | string // Encoding specified for the check if any } ``` -------------------------------- ### Conditional Requirement Limitation Source: https://joi.dev/api/18.x.x Demonstrates that conditional alternatives do not impact the overall requirement status of a key. ```javascript const schema = { a: Joi.alternatives().conditional('b', { is: true, then: Joi.required() }), b: Joi.boolean(), }; ``` -------------------------------- ### Empty Line After Opening Braces Source: https://joi.dev/policies/styleguide Demonstrates the requirement for an empty line after opening braces in specific scopes. ```javascript // Right exports.method = function () { if (condition) { if (otherCondition) { console.log('sometimes'); } if (result && result.statusCode === 200) { console.log('special case'); } console.log('always'); } execute(123, (err) => { console.log(err); }); const empty = {}; }; // Wrong exports.method = function () { if (condition) { if (otherCondition) { console.log('sometimes'); } if (result && result.statusCode === 200) { console.log('special case'); } console.log('always'); } execute(123, (err) => { console.log(err); }); const empty = {}; }; ```