Skip to content

Interface: StringSchema<TSchema>

Schema type for string validation.

Extends

Type Parameters

Type ParameterDefault type
TSchemastring

Properties

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

Methods

$_addRule()

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

Adds a rule to current validation schema.

Parameters

ParameterType
rulestring | AddRuleOptions

Returns

Schema

Inherited from

AnySchema.$_addRule


$_compile()

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

Internally compiles schema.

Parameters

ParameterType
schemaSchemaLike
options?CompileOptions

Returns

Schema

Inherited from

AnySchema.$_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

AnySchema.$_getRule


$_mapLabels()

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

Parameters

ParameterType
pathstring | string[]

Returns

string

Inherited from

AnySchema.$_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

AnySchema.$_modify


$_mutateRebuild()

ts
$_mutateRebuild(): this;

Resets current schema.

Returns

this

Inherited from

AnySchema.$_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

AnySchema.$_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

AnySchema.allow


alphanum()

ts
alphanum(): this;

Requires the string value to only contain a-z, A-Z, and 0-9.

Returns

this


alter()

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

Parameters

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

Returns

this

Inherited from

AnySchema.alter


artifact()

ts
artifact(id: any): this;

Parameters

ParameterType
idany

Returns

this

Inherited from

AnySchema.artifact


base64()

ts
base64(options?: Base64Options): this;

Requires the string value to be a valid base64 string; does not check the decoded value.

Parameters

ParameterType
options?Base64Options

Returns

this


bind()

ts
bind(): this;

Returns

this

Inherited from

AnySchema.bind


cache()

ts
cache(cache?: Cache): this;

Parameters

ParameterType
cache?Cache

Returns

this

Inherited from

AnySchema.cache


case()

ts
case(direction: "upper" | "lower"): this;

Sets the required string case.

Parameters

ParameterType
direction"upper" | "lower"

Returns

this


cast()

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

Parameters

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

Returns

this

Inherited from

AnySchema.cast


concat()

ts
concat(schema: this): this;

Parameters

ParameterType
schemathis

Returns

this

Inherited from

AnySchema.concat


creditCard()

ts
creditCard(): this;

Requires the number to be a credit card number (Using Luhn Algorithm).

Returns

this


custom()

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

Parameters

ParameterType
fnCustomValidator
description?string

Returns

this

Inherited from

AnySchema.custom


dataUri()

ts
dataUri(options?: DataUriOptions): this;

Requires the string value to be a valid data URI string.

Parameters

ParameterType
options?DataUriOptions

Returns

this


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

AnySchema.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 string 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

Returns

this

Overrides

AnySchema.default


describe()

ts
describe(): Description;

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

Returns

Description

Inherited from

AnySchema.describe


description()

ts
description(desc: string): this;

Parameters

ParameterType
descstring

Returns

this

Inherited from

AnySchema.description


disallow()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.disallow


domain()

ts
domain(options?: DomainOptions): this;

Requires the string value to be a valid domain.

Parameters

ParameterType
options?DomainOptions

Returns

this


email()

ts
email(options?: EmailOptions): this;

Requires the string value to be a valid email address.

Parameters

ParameterType
options?EmailOptions

Returns

this


empty()

ts
empty(schema?: SchemaLike): this;

Parameters

ParameterType
schema?SchemaLike

Returns

this

Inherited from

AnySchema.empty


equal()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.equal


error()

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

Parameters

ParameterType
err| Error | ValidationErrorFunction

Returns

this

Inherited from

AnySchema.error


example()

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

Parameters

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

Returns

this

Inherited from

AnySchema.example


exist()

ts
exist(): this;

Returns

this

Inherited from

AnySchema.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

AnySchema.existsInDb


external()

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

Parameters

ParameterType
methodExternalValidationFunction
description?string

Returns

this

Inherited from

AnySchema.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

AnySchema.extract


failover()

ts
failover(value: any): this;

Parameters

ParameterType
valueany

Returns

this

Inherited from

AnySchema.failover


forbidden()

ts
forbidden(): this;

Returns

this

Inherited from

AnySchema.forbidden


fork()

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

Parameters

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

Returns

this

Inherited from

AnySchema.fork


fqdn()

ts
fqdn(): this;

Requires the string value to be a valid fully qualified domain name.

Returns

this

TIP

This does not do fully RFC-compliant validation, but a practical approximation.


guid()

ts
guid(options?: GuidOptions): this;

Requires the string value to be a valid GUID.

Parameters

ParameterType
options?GuidOptions

Returns

this


hex()

ts
hex(options?: HexOptions): this;

Requires the string value to be a valid hexadecimal string.

Parameters

ParameterType
options?HexOptions

Returns

this


hostname()

ts
hostname(): this;

Requires the string value to be a valid hostname as per RFC1123.

Returns

this


id()

ts
id(name?: string): this;

Parameters

ParameterType
name?string

Returns

this

Inherited from

AnySchema.id


insensitive()

ts
insensitive(): this;

Allows the value to match any whitelist of blacklist item in a case insensitive comparison.

Returns

this


invalid()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.invalid


ip()

ts
ip(options?: IpOptions): this;

Requires the string value to be a valid ip address.

Parameters

ParameterType
options?IpOptions

Returns

this


isAsync()

ts
isAsync(): boolean;

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

Returns

boolean

Inherited from

AnySchema.isAsync


isoDate()

ts
isoDate(): this;

Requires the string value to be in valid ISO 8601 date format.

Returns

this


isoDuration()

ts
isoDuration(): this;

Requires the string value to be in valid ISO 8601 duration format.

Returns

this


keep()

ts
keep(): this;

Returns

this

Inherited from

AnySchema.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

AnySchema.knex


label()

ts
label(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

AnySchema.label


length()

ts
length(limit: number | Reference, encoding?: string): this;

Specifies the exact string length required

Parameters

ParameterTypeDescription
limitnumber | Referencethe required string length. It can also be a reference to another field.
encoding?stringif specified, the string length is calculated in bytes using the provided encoding.

Returns

this


lowercase()

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

Returns

this


max()

ts
max(limit: number | Reference, encoding?: string): this;

Specifies the maximum number of string characters.

Parameters

ParameterTypeDescription
limitnumber | Referencethe maximum number of string characters allowed. It can also be a reference to another field.
encoding?stringif specified, the string length is calculated in bytes using the provided encoding.

Returns

this


message()

ts
message(message: string): this;

Parameters

ParameterType
messagestring

Returns

this

Inherited from

AnySchema.message


messages()

ts
messages(messages: LanguageMessages): this;

Parameters

ParameterType
messagesLanguageMessages

Returns

this

Inherited from

AnySchema.messages


meta()

ts
meta(meta: object): this;

Parameters

ParameterType
metaobject

Returns

this

Inherited from

AnySchema.meta


min()

ts
min(limit: number | Reference, encoding?: string): this;

Specifies the minimum number string characters.

Parameters

ParameterTypeDescription
limitnumber | Referencethe minimum number of string characters required. It can also be a reference to another field.
encoding?stringif specified, the string length is calculated in bytes using the provided encoding.

Returns

this


normalize()

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

Parameters

ParameterTypeDescription
form?"NFC" | "NFD" | "NFKC" | "NFKD"The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD

Returns

this


not()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.not


note()

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

Parameters

ParameterType
...notesstring[]

Returns

this

Inherited from

AnySchema.note


only()

ts
only(): this;

Returns

this

Inherited from

AnySchema.only


optional()

ts
optional(): this;

Returns

this

Inherited from

AnySchema.optional


options()

ts
options(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

AnySchema.options


pattern()

ts
pattern(pattern: RegExp, options?: string | StringRegexOptions): this;

Defines a regular expression rule.

Parameters

ParameterTypeDescription
patternRegExpa regular expression object the string value must match against.
options?string | StringRegexOptionsoptional, 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.

Returns

this


preferences()

ts
preferences(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

AnySchema.preferences


prefs()

ts
prefs(options: ValidationOptions): this;

Parameters

ParameterType
optionsValidationOptions

Returns

this

Inherited from

AnySchema.prefs


presence()

ts
presence(mode: PresenceMode): this;

Parameters

ParameterType
modePresenceMode

Returns

this

Inherited from

AnySchema.presence


raw()

ts
raw(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

AnySchema.raw


regex()

ts
regex(pattern: RegExp, options?: string | StringRegexOptions): this;

Defines a regular expression rule.

Parameters

ParameterTypeDescription
patternRegExpa regular expression object the string value must match against.
options?string | StringRegexOptionsoptional, 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.

Returns

this


replace()

ts
replace(pattern: string | RegExp, replacement: string): this;

Replace characters matching the given pattern with the specified replacement string where:

Parameters

ParameterTypeDescription
patternstring | RegExpa regular expression object to match against, or a string of which all occurrences will be replaced.
replacementstringthe string that will replace the pattern.

Returns

this


required()

ts
required(): this;

Returns

this

Inherited from

AnySchema.required


rule()

ts
rule(options: RuleOptions): this;

Parameters

ParameterType
optionsRuleOptions

Returns

this

Inherited from

AnySchema.rule


shared()

ts
shared(ref: Schema): this;

Parameters

ParameterType
refSchema

Returns

this

Inherited from

AnySchema.shared


strict()

ts
strict(isStrict?: boolean): this;

Parameters

ParameterType
isStrict?boolean

Returns

this

Inherited from

AnySchema.strict


strip()

ts
strip(enabled?: boolean): this;

Parameters

ParameterType
enabled?boolean

Returns

this

Inherited from

AnySchema.strip


tag()

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

Parameters

ParameterType
...tagsstring[]

Returns

this

Inherited from

AnySchema.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

AnySchema.tailor


token()

ts
token(): this;

Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.

Returns

this


trim()

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

Parameters

ParameterTypeDescription
enabled?anyoptional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.

Returns

this


truncate()

ts
truncate(enabled?: boolean): this;

Specifies whether the string.max() limit should be used as a truncation.

Parameters

ParameterTypeDescription
enabled?booleanoptional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.

Returns

this


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

AnySchema.uniqueInDb


unit()

ts
unit(name: string): this;

Parameters

ParameterType
namestring

Returns

this

Inherited from

AnySchema.unit


uppercase()

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

Returns

this


uri()

ts
uri(options?: UriOptions): this;

Requires the string value to be a valid RFC 3986 URI.

Parameters

ParameterType
options?UriOptions

Returns

this


uuid()

ts
uuid(options?: GuidOptions): this;

Requires the string value to be a valid GUID.

Parameters

ParameterType
options?GuidOptions

Returns

this


valid()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.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

AnySchema.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

AnySchema.validateAsync


warn()

ts
warn(): this;

Returns

this

Inherited from

AnySchema.warn


warning()

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

Parameters

ParameterType
codestring
contextValidationContext

Returns

this

Inherited from

AnySchema.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

AnySchema.when

Call Signature

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

this

Inherited from

AnySchema.when