Skip to content

Interface: PhoneSchema<TSchema>

Phone number validation schema interface extending AnySchema. Provides methods for validating and formatting phone numbers with various constraints.

Example

typescript
import Joi from "joi";
import { phone } from "./phone";

const extended = Joi.extend(phone);
const schema = extended.phone().country("US").mobile();

const result = schema.validate("+1234567890");

Extends

Type Parameters

Type ParameterDefault typeDescription
TSchemastringThe schema type, defaults to string

Properties

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

Methods

$_addRule()

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

Adds a rule to current validation schema.

Parameters

ParameterType
rulestring | AddRuleOptions

Returns

Schema

Inherited from

ts
Omit.$_addRule;

$_compile()

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

Internally compiles schema.

Parameters

ParameterType
schemaSchemaLike
options?CompileOptions

Returns

Schema

Inherited from

ts
Omit.$_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

ts
Omit.$_getRule;

$_mapLabels()

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

Parameters

ParameterType
pathstring | string[]

Returns

string

Inherited from

ts
Omit.$_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

ts
Omit.$_modify;

$_mutateRebuild()

ts
$_mutateRebuild(): this;

Resets current schema.

Returns

this

Inherited from

ts
Omit.$_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

ts
Omit.$_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

ts
Omit.allow;

alter()

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

Parameters

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

Returns

this

Inherited from

ts
Omit.alter;

artifact()

ts
artifact(id: any): this;

Parameters

ParameterType
idany

Returns

this

Inherited from

ts
Omit.artifact;

bind()

ts
bind(): this;

Returns

this

Inherited from

ts
Omit.bind;

cache()

ts
cache(cache?: Cache): this;

Parameters

ParameterType
cache?Cache

Returns

this

Inherited from

ts
Omit.cache;

cast()

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

Parameters

ParameterType
to"string" | "number" | "object"

Returns

this


concat()

ts
concat(schema: this): this;

Parameters

ParameterType
schemathis

Returns

this

Inherited from

ts
Omit.concat;

country()

ts
country(country:
  | CountryOrUnknown
  | Reference
  | null): this;

Sets the country context for phone number validation.

Parameters

ParameterTypeDescription
country| CountryOrUnknown | Reference | nullCountry code (ISO 3166-1 alpha-2), country name, Joi reference, or null

Returns

this

The schema instance for chaining

Example

typescript
schema.country("US");
schema.country("United States");
schema.country(Joi.ref("countryField"));

custom()

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

Parameters

ParameterType
fnCustomValidator
description?string

Returns

this

Inherited from

ts
Omit.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

ts
Omit.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 value (string, number, object, etc.) - 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

Returns

this

Example

typescript
const schema = joi.string().default("hello world");
const schemaWithFunction = joi
  .number()
  .default((parent, helpers) => parent.someOtherField * 2);

Inherited from

ts
Omit.default;

describe()

ts
describe(): Description;

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

Returns

Description

Inherited from

ts
Omit.describe;

description()

ts
description(desc: string): this;

Parameters

ParameterType
descstring

Returns

this

Inherited from

ts
Omit.description;

disallow()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ts
Omit.disallow;

empty()

ts
empty(schema?: SchemaLike): this;

Parameters

ParameterType
schema?SchemaLike

Returns

this

Inherited from

ts
Omit.empty;

equal()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ts
Omit.equal;

error()

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

Parameters

ParameterType
err| Error | ValidationErrorFunction

Returns

this

Inherited from

ts
Omit.error;

example()

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

Parameters

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

Returns

this

Inherited from

ts
Omit.example;

exist()

ts
exist(): this;

Returns

this

Inherited from

ts
Omit.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

ts
Omit.existsInDb;

external()

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

Parameters

ParameterType
methodExternalValidationFunction
description?string

Returns

this

Inherited from

ts
Omit.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

ts
Omit.extract;

failover()

ts
failover(value: any): this;

Parameters

ParameterType
valueany

Returns

this

Inherited from

ts
Omit.failover;

fixedLine()

ts
fixedLine(): this;

Validates that the phone number is a fixed line or fixed line/mobile number.

Returns

this

The schema instance for chaining


fixedLineOrMobile()

ts
fixedLineOrMobile(): this;

Validates that the phone number is either a fixed line or mobile number.

Returns

this

The schema instance for chaining


forbidden()

ts
forbidden(): this;

Returns

this

Inherited from

ts
Omit.forbidden;

fork()

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

Parameters

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

Returns

this

Inherited from

ts
Omit.fork;

format()

ts
format(as:
  | "raw"
  | "type"
  | "e164"
  | "international"
  | "national"
  | "timezone"
  | "country"): this;

Sets the output format for the phone number.

Parameters

ParameterTypeDescription
as| "raw" | "type" | "e164" | "international" | "national" | "timezone" | "country"The desired output format

Returns

this

The schema instance for chaining

Example

typescript
schema.format("international"); // +1 234 567 8900
schema.format("national"); // (234) 567-8900
schema.format("e164"); // +12345678900

id()

ts
id(name?: string): this;

Parameters

ParameterType
name?string

Returns

this

Inherited from

ts
Omit.id;

invalid()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ts
Omit.invalid;

isAsync()

ts
isAsync(): boolean;

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

Returns

boolean

Inherited from

ts
Omit.isAsync;

keep()

ts
keep(): this;

Returns

this

Inherited from

ts
Omit.keep;

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

ts
Omit.knex;

label()

ts
label(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

ts
Omit.label;

message()

ts
message(message: string): this;

Parameters

ParameterType
messagestring

Returns

this

Inherited from

ts
Omit.message;

messages()

ts
messages(messages: LanguageMessages): this;

Parameters

ParameterType
messagesLanguageMessages

Returns

this

Inherited from

ts
Omit.messages;

meta()

ts
meta(meta: object): this;

Parameters

ParameterType
metaobject

Returns

this

Inherited from

ts
Omit.meta;

mobile()

ts
mobile(): this;

Validates that the phone number is a mobile or fixed line/mobile number.

Returns

this

The schema instance for chaining


not()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ts
Omit.not;

note()

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

Parameters

ParameterType
...notesstring[]

Returns

this

Inherited from

ts
Omit.note;

only()

ts
only(): this;

Returns

this

Inherited from

ts
Omit.only;

optional()

ts
optional(): this;

Returns

this

Inherited from

ts
Omit.optional;

options()

ts
options(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ts
Omit.options;

pager()

ts
pager(): this;

Validates that the phone number is a pager number.

Returns

this

The schema instance for chaining


personalNumber()

ts
personalNumber(): this;

Validates that the phone number is a personal number.

Returns

this

The schema instance for chaining


preferences()

ts
preferences(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ts
Omit.preferences;

prefs()

ts
prefs(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

ts
Omit.prefs;

premiumRate()

ts
premiumRate(): this;

Validates that the phone number is a premium rate number.

Returns

this

The schema instance for chaining


presence()

ts
presence(mode: PresenceMode): this;

Parameters

ParameterType
modePresenceMode

Returns

this

Inherited from

ts
Omit.presence;

raw()

ts
raw(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

ts
Omit.raw;

required()

ts
required(): this;

Returns

this

Inherited from

ts
Omit.required;

rule()

ts
rule(options: RuleOptions): this;

Parameters

ParameterType
optionsRuleOptions

Returns

this

Inherited from

ts
Omit.rule;

shared()

ts
shared(ref: Schema): this;

Parameters

ParameterType
refSchema

Returns

this

Inherited from

ts
Omit.shared;

sharedCost()

ts
sharedCost(): this;

Validates that the phone number is a shared cost number.

Returns

this

The schema instance for chaining


strict()

ts
strict(isStrict?: boolean): this;

Parameters

ParameterType
isStrict?boolean

Returns

this

Inherited from

ts
Omit.strict;

strictFixedLine()

ts
strictFixedLine(): this;

Validates that the phone number is strictly a fixed line number only.

Returns

this

The schema instance for chaining


strictMobile()

ts
strictMobile(): this;

Validates that the phone number is strictly a mobile number only.

Returns

this

The schema instance for chaining


strip()

ts
strip(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

ts
Omit.strip;

tag()

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

Parameters

ParameterType
...tagsstring[]

Returns

this

Inherited from

ts
Omit.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

ts
Omit.tailor;

tollFree()

ts
tollFree(): this;

Validates that the phone number is a toll-free number.

Returns

this

The schema instance for chaining


types()

ts
types(...types: (
  | "FIXED_LINE"
  | "MOBILE"
  | "FIXED_LINE_OR_MOBILE"
  | "TOLL_FREE"
  | "PREMIUM_RATE"
  | "SHARED_COST"
  | "VOIP"
  | "PERSONAL_NUMBER"
  | "PAGER"
  | "UAN"
  | "VOICEMAIL"
  | "UNKNOWN"
  | "INVALID")[]): this;

Validates that the phone number matches one of the specified types.

Parameters

ParameterTypeDescription
...types( | "FIXED_LINE" | "MOBILE" | "FIXED_LINE_OR_MOBILE" | "TOLL_FREE" | "PREMIUM_RATE" | "SHARED_COST" | "VOIP" | "PERSONAL_NUMBER" | "PAGER" | "UAN" | "VOICEMAIL" | "UNKNOWN" | "INVALID")[]Array of phone types to allow

Returns

this

The schema instance for chaining

Example

typescript
schema.types("MOBILE", "FIXED_LINE");

uan()

ts
uan(): this;

Validates that the phone number is a UAN (Universal Access Number).

Returns

this

The schema instance for chaining


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

ts
Omit.uniqueInDb;

unit()

ts
unit(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

ts
Omit.unit;

unknown()

ts
unknown(): this;

Validates that the phone number is of unknown type.

Returns

this

The schema instance for chaining


valid()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

ts
Omit.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

ts
Omit.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

ts
Omit.validateAsync;

voicemail()

ts
voicemail(): this;

Validates that the phone number is a voicemail number.

Returns

this

The schema instance for chaining


voip()

ts
voip(): this;

Validates that the phone number is a VoIP number.

Returns

this

The schema instance for chaining


warn()

ts
warn(): this;

Returns

this

Inherited from

ts
Omit.warn;

warning()

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

Parameters

ParameterType
codestring
contextValidationContext

Returns

this

Inherited from

ts
Omit.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
ts
Omit.when;

Call Signature

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

this

Inherited from
ts
Omit.when;