joi
- Version 17.13.3
- Published
- 531 kB
- 5 dependencies
- BSD-3-Clause license
Install
npm i joi
yarn add joi
pnpm add joi
Overview
Object schema validation
Index
Variables
Interfaces
AnySchema
- $
- allow()
- alter()
- artifact()
- bind()
- cache()
- cast()
- concat()
- custom()
- default()
- describe()
- description()
- disallow()
- empty()
- equal()
- error()
- example()
- exist()
- external()
- extract()
- failover()
- forbidden()
- fork()
- id()
- invalid()
- keep()
- label()
- message()
- messages()
- meta()
- not()
- note()
- only()
- optional()
- options()
- preferences()
- prefs()
- presence()
- raw()
- required()
- rule()
- ruleset
- shared()
- strict()
- strip()
- tag()
- tailor()
- type
- unit()
- valid()
- validate()
- validateAsync()
- warn()
- warning()
- when()
Root
- allow()
- alt()
- alternatives()
- any()
- array()
- assert()
- attempt()
- binary()
- bool()
- boolean()
- build()
- cache
- checkPreferences()
- compile()
- custom()
- date()
- defaults()
- disallow()
- equal()
- exist()
- expression()
- extend()
- forbidden()
- func()
- function()
- in()
- invalid()
- isError()
- isExpression()
- isRef()
- isSchema()
- link()
- not()
- number()
- object()
- optional()
- options()
- override
- preferences()
- prefs()
- ref()
- required()
- string()
- symbol()
- trace()
- types()
- untrace()
- valid()
- ValidationError
- version
- when()
- x()
Type Aliases
- BasicType
- CoerceFunction
- ComparatorFunction
- CustomValidator
- ExtensionBoundSchema
- ExtensionFactory
- ExternalValidationFunction
- GuidVersions
- IsNonPrimitiveSubsetUnion
- IsPrimitiveSubset
- IsUnion
- LanguageMessages
- NullableType
- ObjectPropertiesSchema
- PartialSchemaMap
- PresenceMode
- RuleMethod
- Schema
- SchemaFunction
- SchemaLike
- SchemaLikeWithoutArray
- SchemaMap
- StrictSchemaMap
- Types
- ValidationErrorFunction
- ValidationResult
Variables
variable Joi
const Joi: Joi.Root;
Interfaces
interface AddRuleOptions
interface AddRuleOptions {}
interface AlternativesSchema
interface AlternativesSchema<TSchema = any> extends AnySchema<TSchema> {}
method conditional
conditional: { (ref: string | Reference, options: WhenOptions | WhenOptions[]): this; (ref: Schema<any>, options: WhenSchemaOptions): this;};
Adds a conditional alternative schema type, either based on another key value, or a schema peeking into the current value.
method match
match: (mode: 'any' | 'all' | 'one') => this;
Requires the validated value to match a specific set of the provided alternative.try() schemas. Cannot be combined with
alternatives.conditional()
.
method try
try: (...types: SchemaLikeWithoutArray[]) => this;
Adds an alternative schema type for attempting to match against the validated value.
interface AnySchema
interface AnySchema<TSchema = any> extends SchemaInternals {}
property $
$: this;
Starts a ruleset in order to apply multiple rule options. The set ends when
rule()
,keep()
,message()
, orwarn()
is called.
property ruleset
ruleset: this;
Starts a ruleset in order to apply multiple rule options. The set ends when
rule()
,keep()
,message()
, orwarn()
is called.
property type
type?: Types | string;
method allow
allow: (...values: any[]) => this;
Whitelists a value
method alter
alter: (targets: Record<string, (schema: this) => Schema>) => this;
Assign target alteration options to a schema that are applied when
any.tailor()
is called.Parameter targets
an object where each key is a target name, and each value is a function that takes an schema and returns an schema.
method artifact
artifact: (id: any) => this;
Assigns the schema an artifact id which is included in the validation result if the rule passed validation.
Parameter id
any value other than undefined which will be returned as-is in the result artifacts map.
method bind
bind: () => this;
By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because they use
this
internally. SoJoi.string()
works but if you extract the function from it and callstring()
it won't.bind()
creates a new Joi instance where all the functions relying onthis
are bound to the Joi instance.
method cache
cache: (cache?: Cache) => this;
Adds caching to the schema which will attempt to cache the validation results (success and failures) of incoming inputs. If no cache is passed, a default cache is provisioned by using
cache.provision()
internally.
method cast
cast: (to: 'map' | 'number' | 'set' | 'string') => this;
Casts the validated value to the specified type.
method concat
concat: (schema: this) => this;
Returns a new type that is the result of adding the rules of one type to another.
method custom
custom: (fn: CustomValidator, description?: string) => this;
Adds a custom validation function.
method default
default: ( value?: | BasicType | Reference | ((parent: any, helpers: CustomHelpers) => BasicType | Reference)) => this;
Sets a default value if the original value is
undefined
where:Parameter value
the default value. One of: - a literal value (string, number, object, etc.) - a [references](#refkey-options) - a function which returns the default value using the signature
function(parent, helpers)
where: -parent
- a clone of the object containing the value being validated. Note that since specifying aparent
argument performs cloning, do not declare format arguments if you are not using them. -helpers
- same as those described in [any.custom()
](anycustomermethod_description)When called without any
value
on an object schema type, a default value will be automatically generated based on the default values of the object keys.Note that if value is an object, any changes to the object after
default()
is called will change the reference and any future assignment.
method describe
describe: () => Description;
Returns a plain object representing the schema's rules and properties
method description
description: (desc: string) => this;
Annotates the key
method disallow
disallow: (...values: any[]) => this;
Disallows values.
method empty
empty: (schema?: SchemaLike) => this;
Considers anything that matches the schema to be empty (undefined).
Parameter schema
any object or joi schema to match. An undefined schema unsets that rule.
method equal
equal: (...values: any[]) => this;
Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
method error
error: (err: Error | ValidationErrorFunction) => this;
Overrides the default joi error with a custom error if the rule fails where:
Parameter err
can be: an instance of
Error
- the override error. afunction(errors)
, taking an array of errors as argument, where it must either: return astring
- substitutes the error message with this text return a singleobject
or anArray
of it, where:type
- optional parameter providing the type of the error (eg.number.min
).message
- optional parameter iftemplate
is provided, containing the text of the error.template
- optional parameter ifmessage
is provided, containing a template string, using the same format as usual joi language errors.context
- optional parameter, to provide context to your error if you are using thetemplate
. return anError
- same as when you directly provide anError
, but you can customize the error message based on the errors.Note that if you provide an
Error
, it will be returned as-is, unmodified and undecorated with any of the normal joi error properties. If validation fails and another error is found before the error override, that error will be returned and the override will be ignored (unless theabortEarly
option has been set tofalse
).
method example
example: (value: any, options?: { override: boolean }) => this;
Annotates the key with an example value, must be valid.
method exist
exist: () => this;
Marks a key as required which will not allow undefined as value. All keys are optional by default.
method external
external: (method: ExternalValidationFunction, description?: string) => this;
Adds an external validation rule.
Note that external validation rules are only called after the all other validation rules for the entire schema (from the value root) are checked. This means that any changes made to the value by the external rules are not available to any other validation rules during the non-external validation phase. If schema validation failed, no external validation rules are called.
method extract
extract: (path: string | string[]) => Schema;
Returns a sub-schema based on a path of object keys or schema ids.
Parameter path
a dot
.
separated path string or a pre-split array of path keys. The keys must match the sub-schema id or object key (if no id was explicitly set).
method failover
failover: (value: any) => this;
Sets a failover value if the original value fails passing validation.
Parameter value
the failover value. value supports references. value may be assigned a function which returns the default value.
If value is specified as a function that accepts a single parameter, that parameter will be a context object that can be used to derive the resulting value. Note that if value is an object, any changes to the object after
failover()
is called will change the reference and any future assignment. Use a function when setting a dynamic value (e.g. the current time). Using a function with a single argument performs some internal cloning which has a performance impact. If you do not need access to the context, define the function without any arguments.
method forbidden
forbidden: () => this;
Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
method fork
fork: (key: string | string[] | string[][], adjuster: SchemaFunction) => this;
Returns a new schema where each of the path keys listed have been modified.
Parameter key
an array of key strings, a single key string, or an array of arrays of pre-split key strings.
Parameter adjuster
a function which must return a modified schema.
method id
id: (name?: string) => this;
Sets a schema id for reaching into the schema via
any.extract()
. If no id is set, the schema id defaults to the object key it is associated with. If the schema is used in an array or alternatives type and no id is set, the schema in unreachable.
method invalid
invalid: (...values: any[]) => this;
Disallows values.
method keep
keep: () => this;
Same as
rule({ keep: true })
.Note that
keep()
will terminate the current ruleset and cannot be followed by another rule option. Userule()
to apply multiple rule options.
method label
label: (name: string) => this;
Overrides the key name in error messages.
method message
message: (message: string) => this;
Same as
rule({ message })
.Note that
message()
will terminate the current ruleset and cannot be followed by another rule option. Userule()
to apply multiple rule options.
method messages
messages: (messages: LanguageMessages) => this;
Same as
any.prefs({ messages })
. Note that whileany.message()
applies only to the last rule or ruleset,any.messages()
applies to the entire schema.
method meta
meta: (meta: object) => this;
Attaches metadata to the key.
method not
not: (...values: any[]) => this;
Disallows values.
method note
note: (...notes: string[]) => this;
Annotates the key
method only
only: () => this;
Requires the validated value to match of the provided
any.allow()
values. It has not effect when called together withany.valid()
since it already sets the requirements. When used withany.allow()
it converts it to anany.valid()
.
method optional
optional: () => this;
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.
method options
options: (options: ValidationOptions) => this;
Overrides the global validate() options for the current key and any sub-key.
method preferences
preferences: (options: ValidationOptions) => this;
Overrides the global validate() options for the current key and any sub-key.
method prefs
prefs: (options: ValidationOptions) => this;
Overrides the global validate() options for the current key and any sub-key.
method presence
presence: (mode: PresenceMode) => this;
Sets the presence mode for the schema.
method raw
raw: (enabled?: boolean) => this;
Outputs the original untouched value instead of the casted value.
method required
required: () => this;
Marks a key as required which will not allow undefined as value. All keys are optional by default.
method rule
rule: (options: RuleOptions) => this;
Applies a set of rule options to the current ruleset or last rule added.
When applying rule options, the last rule (e.g.
min()
) is used unless there is an active ruleset defined (e.g.$.min().max()
) in which case the options are applied to all the provided rules. Oncerule()
is called, the previous rules can no longer be modified and any active ruleset is terminated.Rule modifications can only be applied to supported rules. Most of the
any
methods do not support rule modifications because they are implemented using schema flags (e.g.required()
) or special internal implementation (e.g.valid()
). In those cases, use theany.messages()
method to override the error codes for the errors you want to customize.
method shared
shared: (ref: Schema) => this;
Registers a schema to be used by descendants of the current schema in named link references.
method strict
strict: (isStrict?: boolean) => this;
Sets the options.convert options to false which prevent type casting for the current key and any child keys.
method strip
strip: (enabled?: boolean) => this;
Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
Parameter enabled
if true, the value is stripped, otherwise the validated value is retained. Defaults to true.
method tag
tag: (...tags: string[]) => this;
Annotates the key
method tailor
tailor: (targets: string | string[]) => Schema;
Applies any assigned target alterations to a copy of the schema that were applied via
any.alter()
.
method unit
unit: (name: string) => this;
Annotates the key with an unit name.
method valid
valid: (...values: any[]) => this;
Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
method validate
validate: (value: any, options?: ValidationOptions) => ValidationResult<TSchema>;
Validates a value using the schema and options.
method validateAsync
validateAsync: <TOpts extends AsyncValidationOptions>( value: any, options?: TOpts) => Promise< TOpts extends { artifacts: true } | { warnings: true } ? { value: TSchema } & (TOpts extends { artifacts: true } ? { artifacts: Map<any, string[][]> } : {}) & (TOpts extends { warnings: true } ? { warning: ValidationWarning } : {}) : TSchema>;
Validates a value using the schema and options.
method warn
warn: () => this;
Same as
rule({ warn: true })
. Note thatwarn()
will terminate the current ruleset and cannot be followed by another rule option. Userule()
to apply multiple rule options.
method warning
warning: (code: string, context: Context) => this;
Generates a warning. When calling
any.validateAsync()
, set thewarning
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 callingany.validate()
.
method when
when: { (ref: string | Reference, options: WhenOptions | WhenOptions[]): this; (ref: Schema<any>, options: WhenSchemaOptions): this;};
Converts the type into an alternatives type where the conditions are merged into the type definition where:
interface ArraySchema
interface ArraySchema<TSchema = any[]> extends AnySchema<TSchema> {}
method has
has: (schema: SchemaLike) => this;
Verifies that an assertion passes for at least one item in the array, where:
schema
- the validation rules required to satisfy the assertion. If theschema
includes references, they are resolved against the array item being tested, not the value of theref
target.
method items
items: (...types: SchemaLikeWithoutArray[]) => this;
List the types allowed for the array values. If a given type is .required() then there must be a matching item in the array. If a type is .forbidden() then it cannot appear in the array. Required items can be added multiple times to signify that multiple items must be found. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly.
Parameter type
a joi schema object to validate each array item against.
method length
length: (limit: number | Reference) => this;
Specifies the exact number of items in the array.
method max
max: (limit: number | Reference) => this;
Specifies the maximum number of items in the array.
method min
min: (limit: number | Reference) => this;
Specifies the minimum number of items in the array.
method ordered
ordered: (...types: SchemaLikeWithoutArray[]) => this;
Lists the types in sequence order for the array values where:
Parameter type
a joi schema object to validate against each array item in sequence order. type can be multiple values passed as individual arguments. If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly.
method single
single: (enabled?: any) => this;
Allow single values to be checked against rules as if it were provided as an array. enabled can be used with a falsy value to go back to the default behavior.
method sort
sort: (options?: ArraySortOptions) => this;
Sorts the array by given order.
method sparse
sparse: (enabled?: any) => this;
Allow this array to be sparse. enabled can be used with a falsy value to go back to the default behavior.
method unique
unique: ( comparator?: string | ComparatorFunction, options?: ArrayUniqueOptions) => this;
Requires the array values to be unique. Remember that if you provide a custom comparator function, different types can be passed as parameter depending on the rules you set on items. Be aware that a deep equality is performed on elements of the array having a type of object, a performance penalty is to be expected for this kind of operation.
interface ArraySortOptions
interface ArraySortOptions {}
interface ArrayUniqueOptions
interface ArrayUniqueOptions extends HierarchySeparatorOptions {}
property ignoreUndefined
ignoreUndefined?: boolean;
if true, undefined values for the dot notation string comparator will not cause the array to fail on uniqueness.
false
interface AsyncValidationOptions
interface AsyncValidationOptions extends ValidationOptions {}
interface Base64Options
interface Base64Options extends Pick<DataUriOptions, 'paddingRequired'> {}
property urlSafe
urlSafe?: boolean;
if true, uses the URI-safe base64 format which replaces
+
with-
and\
with_
.false
interface BaseValidationOptions
interface BaseValidationOptions {}
property abortEarly
abortEarly?: boolean;
when true, stops validation on the first error, otherwise returns all the errors found.
true
property allowUnknown
allowUnknown?: boolean;
when true, allows object to contain unknown keys which are ignored.
false
property artifacts
artifacts?: boolean;
when true, return artifacts alongside the value.
false
property cache
cache?: boolean;
when true, schema caching is enabled (for schemas with explicit caching rules).
false
property context
context?: Context;
provides an external data set to be used in references
property convert
convert?: boolean;
when true, attempts to cast values to the required types (e.g. a string to a number).
true
property dateFormat
dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';
sets the string format used when converting dates to strings in error messages and casting.
'iso'
property debug
debug?: boolean;
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.
false
property errors
errors?: ErrorFormattingOptions;
error formatting settings.
property externals
externals?: boolean;
if false, the external rules set with
any.external()
are ignored, which is required to ignore any external validations in synchronous mode (or an exception is thrown).true
property noDefaults
noDefaults?: boolean;
when true, do not apply default values.
false
property nonEnumerables
nonEnumerables?: boolean;
when true, inputs are shallow cloned to include non-enumerable properties.
false
property presence
presence?: PresenceMode;
sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'.
'optional'
property skipFunctions
skipFunctions?: boolean;
when true, ignores unknown keys with a function value.
false
property stripUnknown
stripUnknown?: boolean | { arrays?: boolean; objects?: boolean };
remove unknown elements from objects and arrays. - when true, all unknown elements will be removed - when an object: - objects - set to true to remove unknown keys from objects
false
interface BinarySchema
interface BinarySchema<TSchema = Buffer> extends AnySchema<TSchema> {}
method encoding
encoding: (encoding: string) => this;
Sets the string encoding format if a string input is converted to a buffer.
method length
length: (limit: number | Reference) => this;
Specifies the exact length of the buffer:
method max
max: (limit: number | Reference) => this;
Specifies the maximum length of the buffer.
method min
min: (limit: number | Reference) => this;
Specifies the minimum length of the buffer.
interface BooleanSchema
interface BooleanSchema<TSchema = boolean> extends AnySchema<TSchema> {}
method falsy
falsy: (...values: Array<string | number | null>) => this;
Allows for additional values to be considered valid booleans by converting them to false during validation. String comparisons are by default case insensitive, see
boolean.sensitive()
to change this behavior.Parameter values
strings, numbers or arrays of them
method sensitive
sensitive: (enabled?: boolean) => this;
Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion (when not in
strict()
mode) to be matched in a case insensitive manner.
method truthy
truthy: (...values: Array<string | number | null>) => this;
Allows for additional values to be considered valid booleans by converting them to true during validation. String comparisons are by default case insensitive, see
boolean.sensitive()
to change this behavior.Parameter values
strings, numbers or arrays of them
interface Cache
interface Cache {}
interface CacheConfiguration
interface CacheConfiguration {}
method provision
provision: (options?: CacheProvisionOptions) => void;
Provisions a simple LRU cache for caching simple inputs (
undefined
,null
, strings, numbers, and booleans).
interface CacheProvisionOptions
interface CacheProvisionOptions {}
property max
max: number;
number of items to store in the cache before the least used items are dropped.
1000
interface CoerceObject
interface CoerceObject {}
interface CoerceResult
interface CoerceResult {}
interface CompileOptions
interface CompileOptions {}
property legacy
legacy: boolean;
If true and the provided schema is (or contains parts) using an older version of joi, will return a compiled schema that is compatible with the older version. If false, the schema is always compiled using the current version and if older schema components are found, an error is thrown.
interface Context
interface Context {}
property key
key?: string;
property label
label?: string;
property value
value?: any;
index signature
[key: string]: any;
interface CreateErrorOptions
interface CreateErrorOptions {}
interface CustomHelpers
interface CustomHelpers<V = any> {}
property error
error: (code: string, local?: Context, localState?: State) => ErrorReport;
property message
message: (messages: LanguageMessages, local?: Context) => ErrorReport;
property original
original: V;
property prefs
prefs: ValidationOptions;
property schema
schema: ExtensionBoundSchema;
property state
state: State;
property warn
warn: (code: string, local?: Context) => void;
interface DataUriOptions
interface DataUriOptions {}
property paddingRequired
paddingRequired?: boolean;
optional parameter defaulting to true which will require
=
padding if true or make padding optional if falsetrue
interface DateSchema
interface DateSchema<TSchema = Date> extends AnySchema<TSchema> {}
method greater
greater: (date: 'now' | Date | number | string | Reference) => this;
Specifies that the value must be greater than date. Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future. It can also be a reference to another field.
method iso
iso: () => this;
Requires the string value to be in valid ISO 8601 date format.
method less
less: (date: 'now' | Date | number | string | Reference) => this;
Specifies that the value must be less than date. Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future. It can also be a reference to another field.
method max
max: (date: 'now' | Date | number | string | Reference) => this;
Specifies the latest date allowed. Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future. It can also be a reference to another field.
method min
min: (date: 'now' | Date | number | string | Reference) => this;
Specifies the oldest date allowed. Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future. It can also be a reference to another field.
method timestamp
timestamp: (type?: 'javascript' | 'unix') => this;
Requires the value to be a timestamp interval from Unix Time.
Parameter type
the type of timestamp (allowed values are unix or javascript [default])
interface DependencyOptions
interface DependencyOptions extends HierarchySeparatorOptions {}
property isPresent
isPresent?: (resolved: any) => boolean;
overrides the default check for a present value.
(resolved) => resolved !== undefined
interface Description
interface Description {}
property description
description?: string;
property example
example?: any[];
property flags
flags?: object;
property invalids
invalids?: any[];
property label
label?: string;
property metas
metas?: any[];
property notes
notes?: string[];
property options
options?: ValidationOptions;
property tags
tags?: string[];
property type
type?: Types | string;
property unit
unit?: string;
property valids
valids?: any[];
index signature
[key: string]: any;
interface DomainOptions
interface DomainOptions {}
property allowFullyQualified
allowFullyQualified?: boolean;
if
true
, domains ending with a.
character are permittedfalse
property allowUnicode
allowUnicode?: boolean;
If
true
, Unicode characters are permittedtrue
property maxDomainSegments
maxDomainSegments?: number;
The maximum number of domain segments (e.g.
x.y.z
has 3 segments) allowed. Defaults to no limit.Infinity
property minDomainSegments
minDomainSegments?: number;
Number of segments required for the domain.
2
property tlds
tlds?: TopLevelDomainOptions | false;
Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
{ allow: true }
interface EmailOptions
interface EmailOptions {}
property allowFullyQualified
allowFullyQualified?: boolean;
if
true
, domains ending with a.
character are permittedfalse
property allowUnicode
allowUnicode?: boolean;
If
true
, Unicode characters are permittedtrue
property ignoreLength
ignoreLength?: boolean;
if
true
, ignore invalid email length errors.false
property maxDomainSegments
maxDomainSegments?: number;
The maximum number of domain segments (e.g.
x.y.z
has 3 segments) allowed. Defaults to no limit.Infinity
property minDomainSegments
minDomainSegments?: number;
Number of segments required for the domain. Be careful since some domains, such as
io
, directly allow email.2
property multiple
multiple?: boolean;
if true, allows multiple email addresses in a single string, separated by , or the separator characters.
false
property separator
separator?: string | string[];
when multiple is true, overrides the default , separator. String can be a single character or multiple separator characters.
','
property tlds
tlds?: TopLevelDomainOptions | false;
Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
{ allow: true }
interface ErrorFormattingOptions
interface ErrorFormattingOptions {}
property escapeHtml
escapeHtml?: boolean;
when true, error message templates will escape special characters to HTML entities, for security purposes.
false
property label
label?: 'path' | 'key' | false;
defines the value used to set the label context variable.
property language
language?: keyof LanguageMessages;
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')
)
property render
render?: boolean;
when false, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time.
true
property stack
stack?: boolean;
when true, the main error will possess a stack trace, otherwise it will be disabled. Defaults to false for performances reasons. Has no effect on platforms other than V8/node.js as it uses the Stack trace API.
false
property wrap
wrap?: { /** * the characters used around `{#label}` references. Defaults to `'"'`. * * @default '"' */ label?: string | false;
/** * the characters used around array values. Defaults to `'[]'` * * @default '[]' */ array?: string | false;
/** * the characters used around array string values. Defaults to no wrapping. * * @default false */ string?: string | false;};
overrides the way values are wrapped (e.g.
[]
around arrays,""
around labels). 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), orfalse
to disable wrapping.
interface ErrorReport
interface ErrorReport extends Error {}
interface ErrorValidationOptions
interface ErrorValidationOptions extends BaseValidationOptions {}
property messages
messages?: Record<string, LanguageMessageTemplate>;
interface Extension
interface Extension {}
property base
base?: Schema;
property cast
cast?: Record< string, { from(value: any): any; to(value: any, helpers: CustomHelpers): any }>;
undocumented options
property coerce
coerce?: CoerceFunction | CoerceObject;
property flags
flags?: Record<string, ExtensionFlag>;
property manifest
manifest?: { build?(obj: ExtensionBoundSchema, desc: Record<string, any>): any;};
property messages
messages?: LanguageMessages | string;
property modifiers
modifiers?: Record<string, (rule: any, enabled?: boolean) => any>;
property overrides
overrides?: Record<string, (value: any) => Schema>;
property properties
properties?: Record<string, any>;
property rules
rules?: Record<string, ExtensionRule & ThisType<SchemaInternals>>;
property terms
terms?: Record<string, ExtensionTerm>;
property type
type: string | RegExp;
method args
args: (...args: SchemaLike[]) => Schema;
method prepare
prepare: (value: any, helpers: CustomHelpers) => any;
method rebuild
rebuild: (schema: ExtensionBoundSchema) => void;
method validate
validate: (value: any, helpers: CustomHelpers) => any;
interface ExtensionFlag
interface ExtensionFlag {}
interface ExtensionRule
interface ExtensionRule {}
property alias
alias?: string;
alternative name for this rule.
property args
args?: Array<RuleArgs | string>;
list of arguments accepted by
method
.
property convert
convert?: boolean;
Dual rule: converts or validates.
property manifest
manifest?: boolean;
property method
method?: RuleMethod | false;
rule body.
property multi
multi?: boolean;
whether rule supports multiple invocations.
property priority
priority?: boolean;
undocumented flags.
method validate
validate: ( value: any, helpers: any, args: Record<string, any>, options: any) => any;
validation function.
interface ExtensionTerm
interface ExtensionTerm {}
interface ExtensionTermManifest
interface ExtensionTermManifest {}
property mapped
mapped: { from: string; to: string;};
interface ExternalHelpers
interface ExternalHelpers<V = any> {}
property error
error: (code: string, local?: Context) => ErrorReport;
property linked
linked: ExtensionBoundSchema | null;
property message
message: (messages: LanguageMessages, local?: Context) => ErrorReport;
property original
original: V;
property prefs
prefs: ValidationOptions;
property schema
schema: ExtensionBoundSchema;
property state
state: State;
property warn
warn: (code: string, local?: Context) => void;
interface FunctionSchema
interface FunctionSchema<TSchema = Function> extends ObjectSchema<TSchema> {}
method arity
arity: (n: number) => this;
Specifies the arity of the function where:
Parameter n
the arity expected.
method class
class: () => this;
Requires the function to be a class.
method maxArity
maxArity: (n: number) => this;
Specifies the minimal arity of the function where:
Parameter n
the minimal arity expected.
method minArity
minArity: (n: number) => this;
Specifies the minimal arity of the function where:
Parameter n
the minimal arity expected.
interface GetRuleOptions
interface GetRuleOptions {}
interface GuidOptions
interface GuidOptions {}
interface HexOptions
interface HexOptions {}
property byteAligned
byteAligned?: boolean;
hex decoded representation must be byte aligned. false
property prefix
prefix?: boolean | 'optional';
controls whether the prefix
0x
or0X
is allowed (or required) on hex strings. Whentrue
, the prefix must be provided. Whenfalse
, the prefix is forbidden. Whenoptional
, the prefix is allowed but not required.false
interface HierarchySeparatorOptions
interface HierarchySeparatorOptions {}
property separator
separator?: string | false;
overrides the default
.
hierarchy separator. Set to false to treat the key as a literal value.'.'
interface IpOptions
interface IpOptions {}
interface IsSchemaOptions
interface IsSchemaOptions {}
property legacy
legacy: boolean;
If true, will identify schemas from older versions of joi, otherwise will throw an error.
false
interface LanguageMessageTemplate
interface LanguageMessageTemplate {}
interface LinkSchema
interface LinkSchema<TSchema = any> extends AnySchema<TSchema> {}
method concat
concat: (schema: Schema) => this;
Same as
any.concat()
but the schema is merged after the link is resolved which allows merging with schemas of the same type as the resolved link. Will throw an exception during validation if the merged types are not compatible.
method ref
ref: (ref: string) => this;
Initializes the schema after constructions for cases where the schema has to be constructed first and then initialized. If
ref
was not passed to the constructor,link.ref()
must be called prior to usage.
interface ModifyOptions
interface ModifyOptions {}
interface MutateRegisterOptions
interface MutateRegisterOptions {}
interface NumberSchema
interface NumberSchema<TSchema = number> extends AnySchema<TSchema> {}
method greater
greater: (limit: number | Reference) => this;
Specifies that the value must be greater than limit. It can also be a reference to another field.
method integer
integer: () => this;
Requires the number to be an integer (no floating point).
method less
less: (limit: number | Reference) => this;
Specifies that the value must be less than limit. It can also be a reference to another field.
method max
max: (limit: number | Reference) => this;
Specifies the maximum value. It can also be a reference to another field.
method min
min: (limit: number | Reference) => this;
Specifies the minimum value. It can also be a reference to another field.
method multiple
multiple: (base: number | Reference) => this;
Specifies that the value must be a multiple of base.
method negative
negative: () => this;
Requires the number to be negative.
method port
port: () => this;
Requires the number to be a TCP port, so between 0 and 65535.
method positive
positive: () => this;
Requires the number to be positive.
method precision
precision: (limit: number) => this;
Specifies the maximum number of decimal places where:
Parameter limit
the maximum number of decimal places allowed.
method sign
sign: (sign: 'positive' | 'negative') => this;
Requires the number to be negative or positive.
method unsafe
unsafe: (enabled?: any) => this;
Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER).
interface ObjectPatternOptions
interface ObjectPatternOptions {}
property fallthrough
fallthrough?: boolean;
property matches
matches: SchemaLike | Reference;
interface ObjectSchema
interface ObjectSchema<TSchema = any> extends AnySchema<TSchema> {}
method and
and: (...peers: Array<string | DependencyOptions>) => this;
Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
Optional settings must be the last argument.
method append
append: { (schema?: SchemaMap<TSchema>): this; <TSchemaExtended = any, T = TSchemaExtended>( schema?: PartialSchemaMap<T> ): ObjectSchema<T>;};
Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
method assert
assert: (ref: string | Reference, schema: SchemaLike, message?: string) => this;
Verifies an assertion where.
method instance
instance: (constructor: Function, name?: string) => this;
Requires the object to be an instance of a given constructor.
Parameter constructor
the constructor function that the object must be an instance of.
Parameter name
an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
method keys
keys: (schema?: SchemaMap<TSchema>) => this;
Sets or extends the allowed object keys.
method length
length: (limit: number) => this;
Specifies the exact number of keys in the object.
method max
max: (limit: number | Reference) => this;
Specifies the maximum number of keys in the object.
method min
min: (limit: number | Reference) => this;
Specifies the minimum number of keys in the object.
method nand
nand: (...peers: Array<string | DependencyOptions>) => this;
Defines a relationship between keys where not all peers can be present at the same time.
Optional settings must be the last argument.
method or
or: (...peers: Array<string | DependencyOptions>) => this;
Defines a relationship between keys where one of the peers is required (and more than one is allowed).
Optional settings must be the last argument.
method oxor
oxor: (...peers: Array<string | DependencyOptions>) => this;
Defines an exclusive relationship between a set of keys where only one is allowed but none are required.
Optional settings must be the last argument.
method pattern
pattern: ( pattern: RegExp | SchemaLike, schema: SchemaLike, options?: ObjectPatternOptions) => this;
Specify validation rules for unknown keys matching a pattern.
Parameter pattern
a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
Parameter schema
the schema object matching keys must validate against
method ref
ref: () => this;
Requires the object to be a Joi reference.
method regex
regex: () => this;
Requires the object to be a
RegExp
object.
method rename
rename: (from: string | RegExp, to: string, options?: RenameOptions) => this;
Renames a key to another name (deletes the renamed key).
method schema
schema: (type?: SchemaLike) => this;
Requires the object to be a Joi schema instance.
method unknown
unknown: (allow?: boolean) => this;
Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
method with
with: ( key: string, peers: string | string[], options?: DependencyOptions) => this;
Requires the presence of other keys whenever the specified key is present.
method without
without: ( key: string, peers: string | string[], options?: DependencyOptions) => this;
Forbids the presence of other keys whenever the specified is present.
method xor
xor: (...peers: Array<string | DependencyOptions>) => this;
Defines an exclusive relationship between a set of keys. one of them is required but not at the same time.
Optional settings must be the last argument.
interface Reference
interface Reference extends Exclude<ReferenceOptions, 'prefix'> {}
interface ReferenceOptions
interface ReferenceOptions extends HierarchySeparatorOptions {}
property adjust
adjust?: (value: any) => any;
a function with the signature
function(value)
wherevalue
is the resolved reference value and the return value is the adjusted value to use. 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 withmap
.Example 1
(value) => value + 5
property ancestor
ancestor?: number;
If set to a number, sets the reference relative starting point. Cannot be combined with separator prefix characters. Defaults to the reference key prefix (or 1 if none present)
property in
in?: boolean;
creates an in-reference.
property iterables
iterables?: boolean;
when true, the reference resolves by reaching into maps and sets.
property map
map?: Array<[any, any]>;
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 withadjust
.
property prefix
prefix?: { /** * references to the globally provided context preference. * * @default '$' */ global?: string;
/** * references to error-specific or rule specific context. * * @default '#' */ local?: string;
/** * references to the root value being validated. * * @default '/' */ root?: string;};
overrides default prefix characters.
property render
render?: boolean;
when true, the value of the reference is used instead of its name in error messages and template rendering. Defaults to false.
interface RenameOptions
interface RenameOptions {}
property alias
alias?: boolean;
if true, does not delete the old key name, keeping both the new and old keys in place.
false
property ignoreUndefined
ignoreUndefined?: boolean;
if true, skip renaming of a key if it's undefined.
false
property multiple
multiple?: boolean;
if true, allows renaming multiple keys to the same destination where the last rename wins.
false
property override
override?: boolean;
if true, allows renaming a key over an existing key.
false
interface Root
interface Root {}
property cache
cache: CacheConfiguration;
property override
override: symbol;
A special value used with
any.allow()
,any.invalid()
, andany.valid()
as the first value to reset any previously set values.
property ValidationError
ValidationError: new ( message: string, details: ValidationErrorItem[], original: any) => ValidationError;
property version
version: string;
Current version of the joi package.
method allow
allow: (...values: any[]) => Schema;
Whitelists a value
method alt
alt: { <TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>; <TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;};
Alias for
alternatives
method alternatives
alternatives: { <TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>; <TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;};
Generates a type that will match one of the provided alternative schemas
method any
any: <TSchema = any>() => AnySchema<TSchema>;
Generates a schema object that matches any data type.
method array
array: <TSchema = any[]>() => ArraySchema<TSchema>;
Generates a schema object that matches an array data type.
method assert
assert: { (value: any, schema: Schema, options?: ValidationOptions): void; ( value: any, schema: Schema<any>, message: string | Error, options?: ValidationOptions ): void;};
Validates a value against a schema and throws if validation fails.
Parameter value
the value to validate.
Parameter schema
the schema object.
Parameter message
optional message string prefix added in front of the error message. may also be an Error object.
method attempt
attempt: { <TSchema extends Schema<any>>( value: any, schema: TSchema, options?: ValidationOptions ): TSchema extends Schema<infer Value> ? Value : never; <TSchema extends Schema<any>>( value: any, schema: TSchema, message: string | Error, options?: ValidationOptions ): TSchema extends Schema<infer Value> ? Value : never;};
Validates a value against a schema, returns valid object, and throws if validation fails.
Parameter value
the value to validate.
Parameter schema
the schema object.
Parameter message
optional message string prefix added in front of the error message. may also be an Error object.
method binary
binary: <TSchema = Buffer>() => BinarySchema<TSchema>;
Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
method bool
bool: <TSchema = boolean>() => BooleanSchema<TSchema>;
Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via boolean().
method boolean
boolean: <TSchema = boolean>() => BooleanSchema<TSchema>;
Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
method build
build: (...args: any[]) => any;
Unsure, maybe alias for
compile
?
method checkPreferences
checkPreferences: (prefs: ValidationOptions) => void;
Checks if the provided preferences are valid.
Throws an exception if the prefs object is invalid.
The method is provided to perform inputs validation for the
any.validate()
andany.validateAsync()
methods. Validation is not performed automatically for performance reasons. Instead, manually validate the preferences passed once and reuse.
method compile
compile: (schema: SchemaLike, options?: CompileOptions) => Schema;
Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
method custom
custom: (fn: CustomValidator, description?: string) => Schema;
Creates a custom validation schema.
method date
date: <TSchema = Date>() => DateSchema<TSchema>;
Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
method defaults
defaults: (fn: SchemaFunction) => Root;
Creates a new Joi instance that will apply defaults onto newly created schemas through the use of the fn function that takes exactly one argument, the schema being created.
Parameter fn
The function must always return a schema, even if untransformed.
method disallow
disallow: (...values: any[]) => Schema;
method equal
equal: (...values: any[]) => Schema;
method exist
exist: () => Schema;
Alias of
required
.
method expression
expression: (template: string, options?: ReferenceOptions) => any;
Generates a dynamic expression using a template string.
method extend
extend: (...extensions: Array<Extension | ExtensionFactory>) => any;
Creates a new Joi instance customized with the extension(s) you provide included.
method forbidden
forbidden: () => Schema;
Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
method func
func: <TSchema = Function>() => FunctionSchema<TSchema>;
Generates a schema object that matches a function type.
method function
function: <TSchema = Function>() => FunctionSchema<TSchema>;
Generates a schema object that matches a function type.
method in
in: (ref: string, options?: ReferenceOptions) => Reference;
Creates a reference that when resolved, is used as an array of values to match against the rule.
method invalid
invalid: (...values: any[]) => Schema;
Blacklists a value
method isError
isError: (error: any) => error is ValidationError;
Checks whether or not the provided argument is an instance of ValidationError
method isExpression
isExpression: (expression: any) => boolean;
Checks whether or not the provided argument is an expression.
method isRef
isRef: (ref: any) => ref is Reference;
Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
method isSchema
isSchema: (schema: any, options?: CompileOptions) => schema is AnySchema<any>;
Checks whether or not the provided argument is a joi schema.
method link
link: <TSchema = any>(ref?: string) => LinkSchema<TSchema>;
Links to another schema node and reuses it for validation, typically for creative recursive schemas.
Parameter ref
the reference to the linked schema node. Cannot reference itself or its children as well as other links. Links can be expressed in relative terms like value references (
Joi.link('...')
), in absolute terms from the schema run-time root (Joi.link('/a')
), or using schema ids implicitly using object keys or explicitly usingany.id()
(Joi.link('#a.b.c')
).
method not
not: (...values: any[]) => Schema;
method number
number: <TSchema = number>() => NumberSchema<TSchema>;
Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
method object
object: <TSchema = any, isStrict = false, T = TSchema>( schema?: SchemaMap<T, isStrict>) => ObjectSchema<TSchema>;
Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects).
method optional
optional: () => Schema;
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.
method options
options: (...args: any[]) => any;
Unsure, maybe alias for
preferences
?
method preferences
preferences: (options: ValidationOptions) => Schema;
Overrides the global validate() options for the current key and any sub-key.
method prefs
prefs: (options: ValidationOptions) => Schema;
Overrides the global validate() options for the current key and any sub-key.
method ref
ref: (key: string, options?: ReferenceOptions) => Reference;
Generates a reference to the value of the named key.
method required
required: () => Schema;
Marks a key as required which will not allow undefined as value. All keys are optional by default.
method string
string: <TSchema = string>() => StringSchema<TSchema>;
Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
method symbol
symbol: <TSchema = Symbol>() => SymbolSchema<TSchema>;
Generates a schema object that matches any symbol.
method trace
trace: (...args: any[]) => any;
Unsure, maybe leaked from
@hapi/lab/coverage/initialize
method types
types: () => { alternatives: AlternativesSchema; any: AnySchema; array: ArraySchema; binary: BinarySchema; boolean: BooleanSchema; date: DateSchema; function: FunctionSchema; link: LinkSchema; number: NumberSchema; object: ObjectSchema; string: StringSchema; symbol: SymbolSchema;};
Returns an object where each key is a plain joi schema type. Useful for creating type shortcuts using deconstruction. Note that the types are already formed and do not need to be called as functions (e.g.
string
, notstring()
).
method untrace
untrace: (...args: any[]) => any;
method valid
valid: (...values: any[]) => Schema;
Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
method when
when: { ( ref: string | Reference, options: WhenOptions | WhenOptions[] ): AlternativesSchema; (ref: Schema<any>, options: WhenSchemaOptions): AlternativesSchema<any>;};
Converts the type into an alternatives type where the conditions are merged into the type definition where:
method x
x: (template: string, options?: ReferenceOptions) => any;
Generates a dynamic expression using a template string.
interface RuleArgs
interface RuleArgs {}
interface RuleOptions
interface RuleOptions {}
property keep
keep?: boolean;
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 bothmin()
rules instead of the later rule overriding the first.false
property message
message?: string | LanguageMessages;
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()
. The strings can be plain messages or a message template.
property warn
warn?: boolean;
if true, turns any error generated by the ruleset to warnings.
interface SchemaInternals
interface SchemaInternals {}
property $_super
$_super: Schema;
Parent schema object.
property $_terms
$_terms: Record<string, any>;
Terms of current schema.
method $_addRule
$_addRule: (rule: string | AddRuleOptions) => Schema;
Adds a rule to current validation schema.
method $_compile
$_compile: (schema: SchemaLike, options?: CompileOptions) => Schema;
Internally compiles schema.
method $_createError
$_createError: ( code: string, value: any, context: Context, state: State, prefs: ValidationOptions, options?: CreateErrorOptions) => Err;
Creates a joi error object.
method $_getFlag
$_getFlag: (name: string) => any;
Get value from given flag.
method $_getRule
$_getRule: (name: string) => GetRuleOptions | undefined;
Retrieve some rule configuration.
method $_mapLabels
$_mapLabels: (path: string | string[]) => string;
method $_match
$_match: (value: any, state: State, prefs: ValidationOptions) => boolean;
Returns true if validations runs fine on given value.
method $_modify
$_modify: (options?: ModifyOptions) => Schema;
method $_mutateRebuild
$_mutateRebuild: () => this;
Resets current schema.
method $_mutateRegister
$_mutateRegister: (schema: Schema, options?: MutateRegisterOptions) => void;
method $_property
$_property: (name: string) => any;
Get value from given property.
method $_reach
$_reach: (path: string[]) => Schema;
Get schema at given path.
method $_rootReferences
$_rootReferences: () => any;
Get current schema root references.
method $_setFlag
$_setFlag: (flag: string, value: any, options?: SetFlagOptions) => void;
Set flag to given value.
method $_validate
$_validate: ( value: any, state: State, prefs: ValidationOptions) => ValidationResult;
Runs internal validations against given value.
interface SetFlagOptions
interface SetFlagOptions {}
property clone
clone: boolean;
interface State
interface State {}
interface StringRegexOptions
interface StringRegexOptions {}
interface StringSchema
interface StringSchema<TSchema = string> extends AnySchema<TSchema> {}
method alphanum
alphanum: () => this;
Requires the string value to only contain a-z, A-Z, and 0-9.
method base64
base64: (options?: Base64Options) => this;
Requires the string value to be a valid base64 string; does not check the decoded value.
method case
case: (direction: 'upper' | 'lower') => this;
Sets the required string case.
method creditCard
creditCard: () => this;
Requires the number to be a credit card number (Using Luhn Algorithm).
method dataUri
dataUri: (options?: DataUriOptions) => this;
Requires the string value to be a valid data URI string.
method domain
domain: (options?: DomainOptions) => this;
Requires the string value to be a valid domain.
method email
email: (options?: EmailOptions) => this;
Requires the string value to be a valid email address.
method guid
guid: (options?: GuidOptions) => this;
Requires the string value to be a valid GUID.
method hex
hex: (options?: HexOptions) => this;
Requires the string value to be a valid hexadecimal string.
method hostname
hostname: () => this;
Requires the string value to be a valid hostname as per RFC1123.
method insensitive
insensitive: () => this;
Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
method ip
ip: (options?: IpOptions) => this;
Requires the string value to be a valid ip address.
method isoDate
isoDate: () => this;
Requires the string value to be in valid ISO 8601 date format.
method isoDuration
isoDuration: () => this;
Requires the string value to be in valid ISO 8601 duration format.
method length
length: (limit: number | Reference, encoding?: string) => this;
Specifies the exact string length required
Parameter limit
the required string length. It can also be a reference to another field.
Parameter encoding
if specified, the string length is calculated in bytes using the provided encoding.
method lowercase
lowercase: () => this;
Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.
method max
max: (limit: number | Reference, encoding?: string) => this;
Specifies the maximum number of string characters.
Parameter limit
the maximum number of string characters allowed. It can also be a reference to another field.
Parameter encoding
if specified, the string length is calculated in bytes using the provided encoding.
method min
min: (limit: number | Reference, encoding?: string) => this;
Specifies the minimum number string characters.
Parameter limit
the minimum number of string characters required. It can also be a reference to another field.
Parameter encoding
if specified, the string length is calculated in bytes using the provided encoding.
method normalize
normalize: (form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD') => this;
Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized.
Parameter form
The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD
method pattern
pattern: (pattern: RegExp, options?: string | StringRegexOptions) => this;
Defines a regular expression rule.
Parameter pattern
a regular expression object the string value must match against.
Parameter options
optional, can be: Name for patterns (useful with multiple patterns). Defaults to 'required'. An optional configuration object with the following supported properties: name - optional pattern name. invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
method regex
regex: (pattern: RegExp, options?: string | StringRegexOptions) => this;
Defines a regular expression rule.
Parameter pattern
a regular expression object the string value must match against.
Parameter options
optional, can be: Name for patterns (useful with multiple patterns). Defaults to 'required'. An optional configuration object with the following supported properties: name - optional pattern name. invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
method replace
replace: (pattern: RegExp | string, replacement: string) => this;
Replace characters matching the given pattern with the specified replacement string where:
Parameter pattern
a regular expression object to match against, or a string of which all occurrences will be replaced.
Parameter replacement
the string that will replace the pattern.
method token
token: () => this;
Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
method trim
trim: (enabled?: any) => this;
Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
Parameter enabled
optional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.
method truncate
truncate: (enabled?: boolean) => this;
Specifies whether the string.max() limit should be used as a truncation.
Parameter enabled
optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.
method uppercase
uppercase: () => this;
Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.
method uri
uri: (options?: UriOptions) => this;
Requires the string value to be a valid RFC 3986 URI.
method uuid
uuid: (options?: GuidOptions) => this;
Requires the string value to be a valid GUID.
interface SwitchCases
interface SwitchCases {}
interface SwitchDefault
interface SwitchDefault {}
property otherwise
otherwise: SchemaLike;
the alternative schema type if no cases matched. Only one otherwise statement is allowed in switch as the last array item.
interface SymbolSchema
interface SymbolSchema<TSchema = Symbol> extends AnySchema<TSchema> {}
method map
map: ( iterable: | Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }) => this;
interface TopLevelDomainOptions
interface TopLevelDomainOptions {}
property allow
allow?: Set<string> | string[] | boolean;
-
true
to use the IANA list of registered TLDs. This is the default value. -false
to allow any TLD not listed in thedeny
list, if present. - ASet
or array of the allowed TLDs. Cannot be used together withdeny
.
property deny
deny?: Set<string> | string[];
- A
Set
or array of the forbidden TLDs. Cannot be used together with a customallow
list.
interface UriOptions
interface UriOptions {}
property allowQuerySquareBrackets
allowQuerySquareBrackets?: boolean;
Allows unencoded square brackets inside the query string. This is NOT RFC 3986 compliant but query strings like abc[]=123&abc[]=456 are very common these days.
false
property allowRelative
allowRelative?: boolean;
Allow relative URIs.
false
property domain
domain?: DomainOptions;
Validate the domain component using the options specified in
string.domain()
.
property encodeUri
encodeUri?: boolean;
Encode URI before validation.
false
property relativeOnly
relativeOnly?: boolean;
Restrict only relative URIs.
false
property scheme
scheme?: string | RegExp | Array<string | RegExp>;
Specifies one or more acceptable Schemes, should only include the scheme name. Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
interface ValidationError
interface ValidationError extends Error {}
property details
details: ValidationErrorItem[];
array of errors.
property isJoi
isJoi: boolean;
property name
name: 'ValidationError';
method annotate
annotate: (stripColors?: boolean) => string;
function that returns a string with an annotated version of the object pointing at the places where errors occurred.
NOTE: This method does not exist in browser builds of Joi
Parameter stripColors
if truthy, will strip the colors out of the output.
interface ValidationErrorItem
interface ValidationErrorItem {}
interface ValidationOptions
interface ValidationOptions extends BaseValidationOptions {}
property messages
messages?: LanguageMessages;
overrides individual error messages. Defaults to no override (
{}
). Messages use the same rules as templates. Variables in double braces{{var}}
are HTML escaped if the optionerrors.escapeHtml
is set to true.{}
interface ValidationWarning
interface ValidationWarning {}
interface WhenOptions
interface WhenOptions {}
property break
break?: boolean;
whether to stop applying further conditions if the condition is true.
property is
is?: SchemaLike;
the required condition joi type.
property not
not?: SchemaLike;
the negative version of
is
(then
andotherwise
have reverse roles).
property otherwise
otherwise?: SchemaLike;
the alternative schema type if the condition is false. Required if then or switch are missing.
property switch
switch?: Array<SwitchCases | SwitchDefault>;
the list of cases. Required if then is missing. Required if then or otherwise are missing.
property then
then?: SchemaLike;
the alternative schema type if the condition is true. Required if otherwise or switch are missing.
interface WhenSchemaOptions
interface WhenSchemaOptions {}
Type Aliases
type BasicType
type BasicType = boolean | number | string | any[] | object | null;
type CoerceFunction
type CoerceFunction = (value: any, helpers: CustomHelpers) => CoerceResult;
type ComparatorFunction
type ComparatorFunction = (a: any, b: any) => boolean;
type CustomValidator
type CustomValidator<V = any, R = V> = ( value: V, helpers: CustomHelpers<R>) => R | ErrorReport;
type ExtensionBoundSchema
type ExtensionBoundSchema = Schema & SchemaInternals;
type ExtensionFactory
type ExtensionFactory = (joi: Root) => Extension;
type ExternalValidationFunction
type ExternalValidationFunction<V = any, R = V> = ( value: V, helpers: ExternalHelpers<R>) => R | undefined;
type GuidVersions
type GuidVersions = | 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' | 'uuidv6' | 'uuidv7' | 'uuidv8';
type IsNonPrimitiveSubsetUnion
type IsNonPrimitiveSubsetUnion<T> = true extends IsUnion<T> ? true extends IsPrimitiveSubset<T> ? false : true : false;
type IsPrimitiveSubset
type IsPrimitiveSubset<T> = [T] extends [string] ? true : [T] extends [number] ? true : [T] extends [bigint] ? true : [T] extends [boolean] ? true : [T] extends [symbol] ? true : [T] extends [null] ? true : [T] extends [undefined] ? true : false;
type IsUnion
type IsUnion<T, U extends T = T> = T extends unknown ? [U] extends [T] ? false : true : false;
type LanguageMessages
type LanguageMessages = Record<string, string | Record<string, string>>;
type NullableType
type NullableType<T> = undefined | null | T;
type ObjectPropertiesSchema
type ObjectPropertiesSchema<T = any> = true extends IsNonPrimitiveSubsetUnion< Exclude<T, undefined | null>> ? Joi.AlternativesSchema : T extends NullableType<string> ? Joi.StringSchema : T extends NullableType<number> ? Joi.NumberSchema : T extends NullableType<bigint> ? Joi.NumberSchema : T extends NullableType<boolean> ? Joi.BooleanSchema : T extends NullableType<Date> ? Joi.DateSchema : T extends NullableType<Buffer> ? Joi.BinarySchema : T extends NullableType<Array<any>> ? Joi.ArraySchema : T extends NullableType<object> ? StrictSchemaMap<T> | ObjectSchema<T> : never;
type PartialSchemaMap
type PartialSchemaMap<TSchema = any> = { [key in keyof TSchema]?: SchemaLike | SchemaLike[];};
type PresenceMode
type PresenceMode = 'optional' | 'required' | 'forbidden';
type RuleMethod
type RuleMethod = (...args: any[]) => any;
type Schema
type Schema<P = any> = | AnySchema<P> | ArraySchema<P> | AlternativesSchema<P> | BinarySchema<P> | BooleanSchema<P> | DateSchema<P> | FunctionSchema<P> | NumberSchema<P> | ObjectSchema<P> | StringSchema<P> | LinkSchema<P> | SymbolSchema<P>;
type SchemaFunction
type SchemaFunction = (schema: Schema) => Schema;
type SchemaLike
type SchemaLike = SchemaLikeWithoutArray | object;
type SchemaLikeWithoutArray
type SchemaLikeWithoutArray = string | number | boolean | null | Schema | SchemaMap;
type SchemaMap
type SchemaMap<TSchema = any, isStrict = false> = isStrict extends true ? StrictSchemaMap<TSchema> : PartialSchemaMap<TSchema>;
type StrictSchemaMap
type StrictSchemaMap<TSchema = any> = { [key in keyof TSchema]-?: ObjectPropertiesSchema<TSchema[key]>;};
type Types
type Types = | 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'link' | 'number' | 'object' | 'string' | 'symbol';
type ValidationErrorFunction
type ValidationErrorFunction = ( errors: ErrorReport[]) => string | ValidationErrorItem | Error | ErrorReport[];
type ValidationResult
type ValidationResult<TSchema = any> = | { error: undefined; warning?: ValidationError; value: TSchema; } | { error: ValidationError; warning?: ValidationError; value: any; };
Package Files (1)
Dependencies (5)
Dev Dependencies (6)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/joi
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/joi)
- HTML<a href="https://www.jsdocs.io/package/joi"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 8851 ms. - Missing or incorrect documentation? Open an issue for this package.