Skip to content

Interface: FunctionSchema<TSchema>

Schema type for function validation.

Extends

Type Parameters

Type ParameterDefault type
TSchemaFunction

Properties

PropertyModifierTypeDescriptionInherited from
_flagspublicRecord<string, any>Flags of current schema.ObjectSchema._flags
~standardreadonlyProps<TSchema, TSchema>The Standard Schema properties.ObjectSchema.~standard
$publicFunctionSchema<TSchema>Starts a ruleset in order to apply multiple rule options. The set ends when rule(), keep(), message(), or warn() is called.ObjectSchema.$
$_knexpublicany-ObjectSchema.$_knex
$_superpublicSchemaParent schema object.ObjectSchema.$_super
$_termspublicRecord<string, any>Terms of current schema.SchemaInternals.$_terms
rulesetpublicFunctionSchema<TSchema>Starts a ruleset in order to apply multiple rule options. The set ends when rule(), keep(), message(), or warn() is called.ObjectSchema.ruleset
type?publicstring-ObjectSchema.type

Methods

$_addRule()

ts
$_addRule(rule: string | AddRuleOptions): Schema;

Adds a rule to current validation schema.

Parameters

ParameterType
rulestring | AddRuleOptions

Returns

Schema

Inherited from

ObjectSchema.$_addRule


$_compile()

ts
$_compile(schema: SchemaLike, options?: CompileOptions): Schema;

Internally compiles schema.

Parameters

ParameterType
schemaSchemaLike
options?CompileOptions

Returns

Schema

Inherited from

ObjectSchema.$_compile


$_createError()

ts
$_createError(
   code: string,
   value: any,
   context: ValidationContext,
   state: State,
   prefs: ValidationOptions,
   options?: CreateErrorOptions): Err;

Creates a joi error object.

Parameters

ParameterType
codestring
valueany
contextValidationContext
stateState
prefsValidationOptions
options?CreateErrorOptions

Returns

Err

Inherited from

SchemaInternals.$_createError


$_getFlag()

ts
$_getFlag(name: string): any;

Get value from given flag.

Parameters

ParameterType
namestring

Returns

any

Inherited from

SchemaInternals.$_getFlag


$_getRule()

ts
$_getRule(name: string): GetRuleOptions | undefined;

Retrieve some rule configuration.

Parameters

ParameterType
namestring

Returns

GetRuleOptions | undefined

Inherited from

ObjectSchema.$_getRule


$_mapLabels()

ts
$_mapLabels(path: string | string[]): string;

Parameters

ParameterType
pathstring | string[]

Returns

string

Inherited from

ObjectSchema.$_mapLabels


$_match()

ts
$_match(
   value: any,
   state: State,
   prefs: ValidationOptions): boolean;

Returns true if validations runs fine on given value.

Parameters

ParameterType
valueany
stateState
prefsValidationOptions

Returns

boolean

Inherited from

SchemaInternals.$_match


$_modify()

ts
$_modify(options?: ModifyOptions): Schema;

Parameters

ParameterType
options?ModifyOptions

Returns

Schema

Inherited from

ObjectSchema.$_modify


$_mutateRebuild()

ts
$_mutateRebuild(): this;

Resets current schema.

Returns

this

Inherited from

ObjectSchema.$_mutateRebuild


$_mutateRegister()

ts
$_mutateRegister(schema: Schema, options?: MutateRegisterOptions): void;

Parameters

ParameterType
schemaSchema
options?MutateRegisterOptions

Returns

void

Inherited from

SchemaInternals.$_mutateRegister


$_property()

ts
$_property(name: string): any;

Get value from given property.

Parameters

ParameterType
namestring

Returns

any

Inherited from

SchemaInternals.$_property


$_reach()

ts
$_reach(path: string[]): Schema;

Get schema at given path.

Parameters

ParameterType
pathstring[]

Returns

Schema

Inherited from

ObjectSchema.$_reach


$_rootReferences()

ts
$_rootReferences(): any;

Get current schema root references.

Returns

any

Inherited from

SchemaInternals.$_rootReferences


$_setFlag()

ts
$_setFlag(
   flag: string,
   value: any,
   options?: SetFlagOptions): void;

Set flag to given value.

Parameters

ParameterType
flagstring
valueany
options?SetFlagOptions

Returns

void

Inherited from

SchemaInternals.$_setFlag


$_validate()

ts
$_validate(
   value: any,
   state: State,
   prefs: ValidationOptions): ValidationResult;

Runs internal validations against given value.

Parameters

ParameterType
valueany
stateState
prefsValidationOptions

Returns

ValidationResult

Inherited from

SchemaInternals.$_validate


allow()

ts
allow(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.allow


alter()

ts
alter(targets: Record<string, (schema: this) => Schema>): this;

Parameters

ParameterType
targetsRecord<string, (schema: this) => Schema>

Returns

this

Inherited from

ObjectSchema.alter


and()

ts
and(...peers: (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.

Parameters

ParameterType
...peers(string | DependencyOptions)[]

Returns

this

Inherited from

ObjectSchema.and


append()

Call Signature

ts
append(schema?: PartialSchemaMap<TSchema>): this;

Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.

Parameters
ParameterType
schema?PartialSchemaMap<TSchema>
Returns

this

Inherited from

ObjectSchema.append

Call Signature

ts
append<TSchemaExtended, T>(schema?: PartialSchemaMap<T>): ObjectSchema<T>;
Type Parameters
Type ParameterDefault type
TSchemaExtendedany
TTSchemaExtended
Parameters
ParameterType
schema?PartialSchemaMap<T>
Returns

ObjectSchema<T>

Inherited from

ObjectSchema.append


arity()

ts
arity(n: number): this;

Specifies the arity of the function where:

Parameters

ParameterTypeDescription
nnumberthe arity expected.

Returns

this


artifact()

ts
artifact(id: any): this;

Parameters

ParameterType
idany

Returns

this

Inherited from

ObjectSchema.artifact


assert()

ts
assert(
   ref: string | Reference,
   schema: SchemaLike,
   message?: string): this;

Verifies an assertion where.

Parameters

ParameterType
refstring | Reference
schemaSchemaLike
message?string

Returns

this

Inherited from

ObjectSchema.assert


bind()

ts
bind(): this;

Returns

this

Inherited from

ObjectSchema.bind


cache()

ts
cache(cache?: Cache): this;

Parameters

ParameterType
cache?Cache

Returns

this

Inherited from

ObjectSchema.cache


cast()

ts
cast(to: "string" | "number" | "object" | "map" | "set"): this;

Parameters

ParameterType
to"string" | "number" | "object" | "map" | "set"

Returns

this

Inherited from

ObjectSchema.cast


class()

ts
class(): this;

Requires the function to be a class.

Returns

this


concat()

ts
concat(schema: this): this;

Parameters

ParameterType
schemathis

Returns

this

Inherited from

ObjectSchema.concat


custom()

ts
custom(fn: CustomValidator, description?: string): this;

Parameters

ParameterType
fnCustomValidator
description?string

Returns

this

Inherited from

ObjectSchema.custom


db()

ts
db(connection: any): this;

Alias for .knex(). Sets the database connection for database validation rules.

Parameters

ParameterTypeDescription
connectionanyA Knex instance, transaction, or connection configuration

Returns

this

Inherited from

ObjectSchema.db


default()

ts
default(value?: DefaultableValue): this;

Sets a default value if the original value is undefined.

Parameters

ParameterTypeDescription
value?DefaultableValueThe default value. Can be: - A literal object value - A reference to another schema value - A function that returns the default value with signature (parent, helpers) => value - parent - A clone of the object containing the value being validated - helpers - Validation helper functions for custom validation logic 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.

Returns

this

Inherited from

ObjectSchema.default


describe()

ts
describe(): Description;

Returns a plain object representing the schema's rules and properties

Returns

Description

Inherited from

ObjectSchema.describe


description()

ts
description(desc: string): this;

Parameters

ParameterType
descstring

Returns

this

Inherited from

ObjectSchema.description


disallow()

ts
disallow(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.disallow


empty()

ts
empty(schema?: SchemaLike): this;

Parameters

ParameterType
schema?SchemaLike

Returns

this

Inherited from

ObjectSchema.empty


equal()

ts
equal(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.equal


error()

ts
error(err:
  | Error
  | ValidationErrorFunction): this;

Parameters

ParameterType
err| Error | ValidationErrorFunction

Returns

this

Inherited from

ObjectSchema.error


example()

ts
example(value: any, options?: {
  override: boolean;
}): this;

Parameters

ParameterType
valueany
options?{ override: boolean; }
options.override?boolean

Returns

this

Inherited from

ObjectSchema.example


exist()

ts
exist(): this;

Returns

this

Inherited from

ObjectSchema.exist


existsInDb()

ts
existsInDb(
   table: string | Reference,
   column: string | Reference,
   options?: DbValidationOptions): this;

Validates that the value exists in the specified database table and column. Requires .knex() or .db() to be called first to set the database connection.

Parameters

ParameterTypeDescription
tablestring | ReferenceThe database table name (can be a Joi reference)
columnstring | ReferenceThe column name to check (can be a Joi reference)
options?DbValidationOptionsOptional configuration: - caseInsensitive: Perform case-insensitive comparison (default: false) - filter: Async function to add additional WHERE clauses to the query

Returns

this

Example

typescript
const schema = joi.object({
  country_id: joi.number().knex(db).existsInDb("countries", "id"),
  category: joi.string().knex(db).existsInDb("categories", "name", {
    caseInsensitive: true,
  }),
});

Inherited from

ObjectSchema.existsInDb


external()

ts
external(method: ExternalValidationFunction, description?: string): this;

Parameters

ParameterType
methodExternalValidationFunction
description?string

Returns

this

Inherited from

ObjectSchema.external


extract()

ts
extract(path: string | string[]): Schema;

Returns a sub-schema based on a path of object keys or schema ids.

Parameters

ParameterTypeDescription
pathstring | string[]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).

Returns

Schema

Inherited from

ObjectSchema.extract


failover()

ts
failover(value: any): this;

Parameters

ParameterType
valueany

Returns

this

Inherited from

ObjectSchema.failover


forbidden()

ts
forbidden(): this;

Returns

this

Inherited from

ObjectSchema.forbidden


fork()

ts
fork(key: string | string[] | string[][], adjuster: SchemaFunction): this;

Parameters

ParameterType
keystring | string[] | string[][]
adjusterSchemaFunction

Returns

this

Inherited from

ObjectSchema.fork


id()

ts
id(name?: string): this;

Parameters

ParameterType
name?string

Returns

this

Inherited from

ObjectSchema.id


instance()

ts
instance(constructor: Function, name?: string): this;

Requires the object to be an instance of a given constructor.

Parameters

ParameterTypeDescription
constructorFunctionthe constructor function that the object must be an instance of.
name?stringan alternate name to use in validation errors. This is useful when the constructor function does not have a name.

Returns

this

Inherited from

ObjectSchema.instance


invalid()

ts
invalid(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.invalid


isAsync()

ts
isAsync(): boolean;

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

Returns

boolean

Inherited from

ObjectSchema.isAsync


keep()

ts
keep(): this;

Returns

this

Inherited from

ObjectSchema.keep


keys()

ts
keys(schema?: PartialSchemaMap<TSchema>): this;

Sets or extends the allowed object keys.

Parameters

ParameterType
schema?PartialSchemaMap<TSchema>

Returns

this

Inherited from

ObjectSchema.keys


knex()

ts
knex(connection: any): this;

Sets the database connection for database validation rules. This must be called before using .uniqueInDb() or .existsInDb().

Parameters

ParameterTypeDescription
connectionanyA Knex instance, transaction, or connection configuration

Returns

this

Example

typescript
import knex from 'knex'
const db = knex({ client: 'pg', connection: {...} })
const schema = joi.string().knex(db).uniqueInDb('users', 'email')

Inherited from

ObjectSchema.knex


label()

ts
label(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

ObjectSchema.label


length()

ts
length(limit: number): this;

Specifies the exact number of keys in the object.

Parameters

ParameterType
limitnumber

Returns

this

Inherited from

ObjectSchema.length


max()

ts
max(limit: number | Reference): this;

Specifies the maximum number of keys in the object.

Parameters

ParameterType
limitnumber | Reference

Returns

this

Inherited from

ObjectSchema.max


maxArity()

ts
maxArity(n: number): this;

Specifies the minimal arity of the function where:

Parameters

ParameterTypeDescription
nnumberthe minimal arity expected.

Returns

this


message()

ts
message(message: string): this;

Parameters

ParameterType
messagestring

Returns

this

Inherited from

ObjectSchema.message


messages()

ts
messages(messages: LanguageMessages): this;

Parameters

ParameterType
messagesLanguageMessages

Returns

this

Inherited from

ObjectSchema.messages


meta()

ts
meta(meta: object): this;

Parameters

ParameterType
metaobject

Returns

this

Inherited from

ObjectSchema.meta


min()

ts
min(limit: number | Reference): this;

Specifies the minimum number of keys in the object.

Parameters

ParameterType
limitnumber | Reference

Returns

this

Inherited from

ObjectSchema.min


minArity()

ts
minArity(n: number): this;

Specifies the minimal arity of the function where:

Parameters

ParameterTypeDescription
nnumberthe minimal arity expected.

Returns

this


nand()

ts
nand(...peers: (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.

Parameters

ParameterType
...peers(string | DependencyOptions)[]

Returns

this

Inherited from

ObjectSchema.nand


not()

ts
not(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.not


note()

ts
note(...notes: string[]): this;

Parameters

ParameterType
...notesstring[]

Returns

this

Inherited from

ObjectSchema.note


only()

ts
only(): this;

Returns

this

Inherited from

ObjectSchema.only


optional()

ts
optional(): this;

Returns

this

Inherited from

ObjectSchema.optional


options()

ts
options(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ObjectSchema.options


or()

ts
or(...peers: (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.

Parameters

ParameterType
...peers(string | DependencyOptions)[]

Returns

this

Inherited from

ObjectSchema.or


oxor()

ts
oxor(...peers: (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.

Parameters

ParameterType
...peers(string | DependencyOptions)[]

Returns

this

Inherited from

ObjectSchema.oxor


pattern()

ts
pattern(
   pattern: RegExp | SchemaLike,
   schema: SchemaLike,
   options?: ObjectPatternOptions): this;

Specify validation rules for unknown keys matching a pattern.

Parameters

ParameterTypeDescription
patternRegExp | SchemaLikea pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
schemaSchemaLikethe schema object matching keys must validate against
options?ObjectPatternOptions-

Returns

this

Inherited from

ObjectSchema.pattern


preferences()

ts
preferences(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ObjectSchema.preferences


prefs()

ts
prefs(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ObjectSchema.prefs


presence()

ts
presence(mode: PresenceMode): this;

Parameters

ParameterType
modePresenceMode

Returns

this

Inherited from

ObjectSchema.presence


raw()

ts
raw(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

ObjectSchema.raw


ref()

ts
ref(): this;

Requires the object to be a Joi reference.

Returns

this

Inherited from

ObjectSchema.ref


regex()

ts
regex(): this;

Requires the object to be a RegExp object.

Returns

this

Inherited from

ObjectSchema.regex


rename()

ts
rename(
   from: string | RegExp,
   to: string,
   options?: RenameOptions): this;

Renames a key to another name (deletes the renamed key).

Parameters

ParameterType
fromstring | RegExp
tostring
options?RenameOptions

Returns

this

Inherited from

ObjectSchema.rename


required()

ts
required(): this;

Returns

this

Inherited from

ObjectSchema.required


rule()

ts
rule(options: RuleOptions): this;

Parameters

ParameterType
optionsRuleOptions

Returns

this

Inherited from

ObjectSchema.rule


schema()

ts
schema(type?: SchemaLike): this;

Requires the object to be a Joi schema instance.

Parameters

ParameterType
type?SchemaLike

Returns

this

Inherited from

ObjectSchema.schema


shared()

ts
shared(ref: Schema): this;

Parameters

ParameterType
refSchema

Returns

this

Inherited from

ObjectSchema.shared


strict()

ts
strict(isStrict?: boolean): this;

Parameters

ParameterType
isStrict?boolean

Returns

this

Inherited from

ObjectSchema.strict


strip()

ts
strip(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

ObjectSchema.strip


tag()

ts
tag(...tags: string[]): this;

Parameters

ParameterType
...tagsstring[]

Returns

this

Inherited from

ObjectSchema.tag


tailor()

ts
tailor(targets: string | string[]): Schema;

Applies any assigned target alterations to a copy of the schema that were applied via any.alter().

Parameters

ParameterType
targetsstring | string[]

Returns

Schema

Inherited from

ObjectSchema.tailor


uniqueInDb()

ts
uniqueInDb(
   table: string | Reference,
   column: string | Reference,
   options?: DbValidationOptions): this;

Validates that the value is unique in the specified database table and column. Requires .knex() or .db() to be called first to set the database connection.

Parameters

ParameterTypeDescription
tablestring | ReferenceThe database table name (can be a Joi reference)
columnstring | ReferenceThe column name to check (can be a Joi reference)
options?DbValidationOptionsOptional configuration: - caseInsensitive: Perform case-insensitive comparison (default: false) - filter: Async function to add additional WHERE clauses to the query

Returns

this

Example

typescript
const schema = joi.object({
  email: joi.string().email().knex(db).uniqueInDb("users", "email"),
  username: joi
    .string()
    .knex(db)
    .uniqueInDb("users", "username", {
      caseInsensitive: true,
      filter: async (query) => query.where("tenant_id", tenantId),
    }),
});

Inherited from

ObjectSchema.uniqueInDb


unit()

ts
unit(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

ObjectSchema.unit


unknown()

ts
unknown(allow?: boolean): this;

Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).

Parameters

ParameterType
allow?boolean

Returns

this

Inherited from

ObjectSchema.unknown


valid()

ts
valid(...values: any[]): this;

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ObjectSchema.valid


validate()

ts
validate(value: any, options?: ValidationOptions): ValidationResult<TSchema>;

Validates a value using the schema and options.

Parameters

ParameterType
valueany
options?ValidationOptions

Returns

ValidationResult<TSchema>

Inherited from

ObjectSchema.validate


validateAsync()

ts
validateAsync<TOpts>(value: any, options?: TOpts): Promise<TOpts extends
  | {
  artifacts: true;
}
  | {
  warnings: true;
} ? {
  value: TSchema;
} & TOpts<TOpts> extends {
  artifacts: true;
} ? {
  artifacts: Map<any, string[][]>;
} : {
} & TOpts<TOpts> extends {
  warnings: true;
} ? {
  warning: ValidationWarning;
} : {
} : TSchema>;

Validates a value using the schema and options.

Type Parameters

Type Parameter
TOpts extends AsyncValidationOptions

Parameters

ParameterType
valueany
options?TOpts

Returns

Promise<TOpts extends | { artifacts: true; } | { warnings: true; } ? { value: TSchema; } & TOpts<TOpts> extends { artifacts: true; } ? { artifacts: Map<any, string[][]>; } : { } & TOpts<TOpts> extends { warnings: true; } ? { warning: ValidationWarning; } : { } : TSchema>

Inherited from

ObjectSchema.validateAsync


warn()

ts
warn(): this;

Returns

this

Inherited from

ObjectSchema.warn


warning()

ts
warning(code: string, context: ValidationContext): this;

Parameters

ParameterType
codestring
contextValidationContext

Returns

this

Inherited from

ObjectSchema.warning


when()

Call Signature

ts
when(ref: string | Reference, options:
  | WhenOptions<any, any>
  | WhenOptions<any, any>[]): this;
Parameters
ParameterType
refstring | Reference
options| WhenOptions<any, any> | WhenOptions<any, any>[]
Returns

this

Inherited from

ObjectSchema.when

Call Signature

ts
when(ref: Schema, options: WhenSchemaOptions): this;
Parameters
ParameterType
refSchema
optionsWhenSchemaOptions
Returns

this

Inherited from

ObjectSchema.when


with()

ts
with(
   key: string,
   peers: string | string[],
   options?: DependencyOptions): this;

Requires the presence of other keys whenever the specified key is present.

Parameters

ParameterType
keystring
peersstring | string[]
options?DependencyOptions

Returns

this

Inherited from

ObjectSchema.with


without()

ts
without(
   key: string,
   peers: string | string[],
   options?: DependencyOptions): this;

Forbids the presence of other keys whenever the specified is present.

Parameters

ParameterType
keystring
peersstring | string[]
options?DependencyOptions

Returns

this

Inherited from

ObjectSchema.without


xor()

ts
xor(...peers: (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.

Parameters

ParameterType
...peers(string | DependencyOptions)[]

Returns

this

Inherited from

ObjectSchema.xor