Skip to content

Interface: DatetimeSchema<TSchema>

Schema for datetime validation with comprehensive formatting and comparison methods.

Extends the base AnySchema to provide datetime-specific validation rules including comparisons (before/after), weekend/weekday checks, timezone conversions, and various output formatting options.

Supports keyword values for intuitive date comparisons like 'today', 'yesterday', 'start of month', 'next week', etc. See Parseable for full list.

Examples

typescript
const schema: DatetimeSchema = joi
  .datetime()
  .after("2023-01-01")
  .toUTC()
  .toISO();

const result = schema.validate("2023-06-15T10:30:00Z");
// Returns ISO string in UTC timezone
typescript
const schema = joi.datetime().after("yesterday").before("tomorrow").weekday();

schema.validate("today"); // Valid if today is a weekday
typescript
// 'today' with beforeOrEqual includes the entire day (00:00 - 23:59:59.999)
joi.datetime().beforeOrEqual("today").validate("2023-12-03T23:59:59Z"); // Valid

// 'today' with after starts from beginning of day (00:00:00)
joi.datetime().after("today").validate("2023-12-03T00:00:01Z"); // Valid

Extends

Type Parameters

Type ParameterDefault typeDescription
TSchemaDateTimeThe output type after validation and potential transformation

Properties

PropertyModifierTypeDescriptionInherited from
_flagspublicRecord<string, any>Flags of current schema.AnySchema._flags
~standardreadonlyProps<TSchema, TSchema>The Standard Schema properties.AnySchema.~standard
$publicDatetimeSchema<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
rulesetpublicDatetimeSchema<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


after()

ts
after(limit: Reference | Parseable): this;

Validates that the datetime is after the specified limit.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be after (supports keywords)

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().after("2023-01-01T00:00:00Z");
schema.validate("2023-01-02T00:00:00Z"); // Valid
schema.validate("2022-12-31T23:59:59Z"); // Invalid
typescript
const schema = joi.datetime().after("today");
schema.validate(DateTime.now().plus({ days: 1 })); // Valid
schema.validate(DateTime.now().minus({ days: 1 })); // Invalid

afterOrEqual()

ts
afterOrEqual(limit: Reference | Parseable): this;

Validates that the datetime is after or equal to the specified limit.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be after or equal to

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().afterOrEqual("2023-01-01T00:00:00Z");
schema.validate("2023-01-01T00:00:00Z"); // Valid (equal)
schema.validate("2023-01-02T00:00:00Z"); // Valid (after)
schema.validate("2022-12-31T23:59:59Z"); // Invalid

allow()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.allow


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


before()

ts
before(limit: Reference | Parseable): this;

Validates that the datetime is before the specified limit.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be before (supports keywords)

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().before("2023-12-31T23:59:59Z");
schema.validate("2023-06-15T12:00:00Z"); // Valid
schema.validate("2024-01-01T00:00:00Z"); // Invalid
typescript
const schema = joi.datetime().before("end of month");
schema.validate(DateTime.now().endOf("month").minus({ hours: 1 })); // Valid

beforeOrEqual()

ts
beforeOrEqual(limit: Reference | Parseable): this;

Validates that the datetime is before or equal to the specified limit.

When using period keywords (e.g., 'today', 'last month'), this method intelligently uses the end of the period, making "on or before today" include the entire day.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be before or equal to (supports keywords)

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().beforeOrEqual("2023-12-31T23:59:59Z");
schema.validate("2023-12-31T23:59:59Z"); // Valid (equal)
schema.validate("2023-06-15T12:00:00Z"); // Valid (before)
schema.validate("2024-01-01T00:00:00Z"); // Invalid
typescript
// 'today' resolves to end of day (23:59:59.999) for intuitive behavior
const schema = joi.datetime().beforeOrEqual("today");
schema.validate(DateTime.now()); // Valid (anytime today)
schema.validate(DateTime.now().plus({ days: 1 })); // Invalid (tomorrow)

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


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


custom()

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

Parameters

ParameterType
fnCustomValidator
description?string

Returns

this

Inherited from

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

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

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


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


equals()

ts
equals(limit: Reference | Parseable): this;

Validates that the datetime is equal to the specified limit. Uses loose equality comparison (==) between DateTime objects.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value to compare against

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().equals("2023-01-01T00:00:00Z");
schema.validate("2023-01-01T00:00:00.000Z"); // Valid (same moment)

error()

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

Parameters

ParameterType
err| Error | ValidationErrorFunction

Returns

this

Inherited from

AnySchema.error


exactly()

ts
exactly(limit: Reference | Parseable): this;

Validates that the datetime is exactly equal to the specified limit. Uses strict equality comparison (===) between DateTime objects.

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value to compare against

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().exactly("2023-01-01T00:00:00Z");
schema.validate("2023-01-01T00:00:00Z"); // Valid
schema.validate("2023-01-01T00:00:01Z"); // Invalid

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


greater()

ts
greater(limit: Reference | Parseable): this;

Validates that the datetime is greater than the specified limit. Alias for after().

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be greater than

Returns

this

The schema instance for method chaining


id()

ts
id(name?: string): this;

Parameters

ParameterType
name?string

Returns

this

Inherited from

AnySchema.id


invalid()

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

Parameters

ParameterType
...valuesany[]

Returns

this

Inherited from

AnySchema.invalid


isAsync()

ts
isAsync(): boolean;

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

Returns

boolean

Inherited from

AnySchema.isAsync


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


less()

ts
less(limit: Reference | Parseable): this;

Validates that the datetime is less than the specified limit. Alias for before().

Parameters

ParameterTypeDescription
limitReference | ParseableThe datetime value that the input must be less than

Returns

this

The schema instance for method chaining


max()

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

Validates that the datetime is less than or equal to the specified limit. Alias for beforeOrEqual().

Parameters

ParameterTypeDescription
limitReference | ParseableThe maximum datetime value

Returns

this

The schema instance for method chaining


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: Reference | Parseable): this;

Validates that the datetime is greater than or equal to the specified limit. Alias for afterOrEqual().

Parameters

ParameterTypeDescription
limitReference | ParseableThe minimum datetime value

Returns

this

The schema instance for method chaining


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


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


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


setLocale()

ts
setLocale(locale: string): this;

Sets the locale for the datetime during validation.

Parameters

ParameterTypeDescription
localestringThe locale code (e.g., 'en-US', 'fr-FR')

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().setLocale("fr-FR").toLocaleString();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns localized string in French

setZone()

ts
setZone(zone: string | Zone<boolean>, opts?: ZoneOptions): this;

Sets the timezone for the datetime during validation.

Parameters

ParameterTypeDescription
zonestring | Zone<boolean>The timezone to set (IANA timezone name or Luxon Zone object)
opts?ZoneOptions-

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().setZone("America/New_York");
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns DateTime in Eastern timezone

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


toBSON()

ts
toBSON(): this;

Converts the datetime to BSON format during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toBSON();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: Date object for BSON serialization

toFormat()

ts
toFormat(format: CallbackOrValue<string>): this;

Formats the datetime using a custom format string during validation.

Parameters

ParameterTypeDescription
formatCallbackOrValue<string>The format string (Luxon format tokens) or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toFormat("yyyy-MM-dd HH:mm:ss");
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-07-15 15:30:00"
typescript
const schema = joi
  .datetime()
  .toFormat((dt, helpers) => (dt.year > 2000 ? "yyyy-MM-dd" : "MM/dd/yy"));

toHTTP()

ts
toHTTP(): this;

Converts the datetime to HTTP date format during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toHTTP();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "Sat, 15 Jul 2023 15:30:00 GMT"

toISO()

ts
toISO(opts?: CallbackOrValue<ToISOTimeOptions>): this;

Converts the datetime to ISO 8601 string format during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToISOTimeOptions>Options for ISO string formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toISO({ suppressMilliseconds: true });
const result = schema.validate("July 15, 2023 3:30 PM");
// Returns: "2023-07-15T15:30:00Z"
typescript
const schema = joi.datetime().toISO((dt, helpers) => ({
  suppressMilliseconds: true,
  extendedZone: dt.year > 1970,
  precision: "seconds",
}));

toISODate()

ts
toISODate(opts?: CallbackOrValue<ToISODateOptions>): this;

Converts the datetime to ISO date format (YYYY-MM-DD) during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToISODateOptions>Options for ISO date formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toISODate();
const result = schema.validate("July 15, 2023 3:30 PM");
// Returns: "2023-07-15"
typescript
const schema = joi.datetime().toISODate((dt, helpers) => ({
  format: dt.year > 2000 ? "extended" : "basic",
}));

toISOTime()

ts
toISOTime(opts?: CallbackOrValue<ToISOTimeOptions>): this;

Converts the datetime to ISO time format during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToISOTimeOptions>Options for ISO time formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toISOTime({ suppressMilliseconds: true });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "15:30:00Z"
typescript
const schema = joi.datetime().toISOTime((dt, helpers) => ({
  suppressMilliseconds: dt.millisecond === 0,
}));

toISOWeekDate()

ts
toISOWeekDate(): this;

Converts the datetime to ISO week date format during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toISOWeekDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-W28-6"

toJSDate()

ts
toJSDate(): this;

Converts the datetime to a JavaScript Date object during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toJSDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: Date object

toJSON()

ts
toJSON(): this;

Converts the datetime to JSON string format during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toJSON();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-07-15T15:30:00.000Z"

toLocal()

ts
toLocal(): this;

Converts the datetime to local timezone during validation. The output will be a DateTime object in the system's local timezone.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toLocal();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns DateTime in local timezone

toLocalizedString()

ts
toLocalizedString(formatOpts: CallbackOrValue<LocaleOptions>): this;

Formats the datetime using locale-specific formatting during validation.

Parameters

ParameterTypeDescription
formatOptsCallbackOrValue<LocaleOptions>Locale formatting options or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi
  .datetime()
  .toLocalizedString({ month: "long", day: "numeric" });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "July 15" (or localized equivalent)
typescript
const schema = joi.datetime().toLocalizedString((dt, helpers) => ({
  month: dt.month > 6 ? "long" : "short",
  day: "numeric",
}));

toMillis()

ts
toMillis(): this;

Converts the datetime to milliseconds since Unix epoch during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toMillis();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800000

toObject()

ts
toObject(opts?: CallbackOrValue<{
  includeConfig?: boolean;
}>): this;

Converts the datetime to a plain object representation during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<{ includeConfig?: boolean; }>Options for object conversion or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toObject({ includeConfig: true });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: { year: 2023, month: 7, day: 15, hour: 15, minute: 30, second: 0, millisecond: 0 }
typescript
const schema = joi.datetime().toObject((dt, helpers) => ({
  includeConfig: dt.year > 2000,
}));

toRelative()

ts
toRelative(opts?: CallbackOrValue<ToRelativeOptions>): this;

Converts the datetime to a relative time string during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToRelativeOptions>Options for relative time formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toRelative({ base: DateTime.now() });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2 hours ago" (relative to current time)
typescript
const schema = joi.datetime().toRelative((dt, helpers) => ({
  base: dt.year > 2020 ? DateTime.now() : DateTime.fromISO("2020-01-01"),
}));

toRFC2822()

ts
toRFC2822(): this;

Converts the datetime to RFC 2822 format during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toRFC2822();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "Sat, 15 Jul 2023 15:30:00 +0000"

toSeconds()

ts
toSeconds(): this;

Converts the datetime to seconds since Unix epoch during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toSeconds();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800.0

toSQL()

ts
toSQL(opts?: CallbackOrValue<ToSQLOptions>): this;

Converts the datetime to SQL datetime format during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToSQLOptions>Options for SQL formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toSQL({ includeZone: false });
const result = schema.validate("2023-07-15T15:30:45.123Z");
// Returns: "2023-07-15 15:30:45.123"
typescript
const schema = joi.datetime().toSQL((dt, helpers) => ({
  includeZone: dt.zone.name !== "UTC",
}));

toSQLDate()

ts
toSQLDate(): this;

Converts the datetime to SQL date format (YYYY-MM-DD) during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toSQLDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-07-15"

toSQLTime()

ts
toSQLTime(opts?: CallbackOrValue<ToSQLOptions>): this;

Converts the datetime to SQL time format (HH:mm:ss.SSS) during validation.

Parameters

ParameterTypeDescription
opts?CallbackOrValue<ToSQLOptions>Options for SQL time formatting or callback function

Returns

this

The schema instance for method chaining

Examples

typescript
const schema = joi.datetime().toSQLTime({ includeZone: true });
const result = schema.validate("2023-07-15T15:30:45.123Z");
// Returns: "15:30:45.123 Z"
typescript
const schema = joi.datetime().toSQLTime((dt, helpers) => ({
  includeZone: dt.zone.name !== "UTC",
}));

toUnixInteger()

ts
toUnixInteger(): this;

Converts the datetime to Unix timestamp (seconds as integer) during validation.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toUnixInteger();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800

toUTC()

ts
toUTC(): this;

Converts the datetime to UTC timezone during validation. The output will be a DateTime object in UTC.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().toUTC();
const result = schema.validate("2023-07-15T10:30:00-05:00");
// Returns DateTime in UTC: 2023-07-15T15:30:00Z

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


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


weekday()

ts
weekday(): this;

Validates that the datetime falls on a weekday (non-weekend day). Based on the configured weekend days in Luxon settings.

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().weekday();
schema.validate("2023-07-03T12:00:00Z"); // Valid if Monday
schema.validate("2023-07-01T12:00:00Z"); // Invalid if Saturday

weekend()

ts
weekend(): this;

Validates that the datetime falls on a weekend day. Based on the configured weekend days in Luxon settings (default: Saturday and Sunday).

Returns

this

The schema instance for method chaining

Example

typescript
const schema = joi.datetime().weekend();
schema.validate("2023-07-01T12:00:00Z"); // Valid if Saturday
schema.validate("2023-07-03T12:00:00Z"); // Invalid if Monday

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