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
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 timezoneconst schema = joi.datetime().after("yesterday").before("tomorrow").weekday();
schema.validate("today"); // Valid if today is a weekday// '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"); // ValidExtends
AnySchema<TSchema>
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TSchema | DateTime | The output type after validation and potential transformation |
Properties
| Property | Modifier | Type | Description | Inherited from |
|---|---|---|---|---|
_flags | public | Record<string, any> | Flags of current schema. | AnySchema._flags |
~standard | readonly | Props<TSchema, TSchema> | The Standard Schema properties. | AnySchema.~standard |
$ | public | DatetimeSchema<TSchema> | Starts a ruleset in order to apply multiple rule options. The set ends when rule(), keep(), message(), or warn() is called. | AnySchema.$ |
$_knex | public | any | - | AnySchema.$_knex |
$_super | public | Schema | Parent schema object. | AnySchema.$_super |
$_terms | public | Record<string, any> | Terms of current schema. | SchemaInternals.$_terms |
ruleset | public | DatetimeSchema<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? | public | string | - | AnySchema.type |
Methods
$_addRule()
$_addRule(rule: string | AddRuleOptions): Schema;Adds a rule to current validation schema.
Parameters
| Parameter | Type |
|---|---|
rule | string | AddRuleOptions |
Returns
Inherited from
$_compile()
$_compile(schema: SchemaLike, options?: CompileOptions): Schema;Internally compiles schema.
Parameters
| Parameter | Type |
|---|---|
schema | SchemaLike |
options? | CompileOptions |
Returns
Inherited from
$_createError()
$_createError(
code: string,
value: any,
context: ValidationContext,
state: State,
prefs: ValidationOptions,
options?: CreateErrorOptions): Err;Creates a joi error object.
Parameters
| Parameter | Type |
|---|---|
code | string |
value | any |
context | ValidationContext |
state | State |
prefs | ValidationOptions |
options? | CreateErrorOptions |
Returns
Inherited from
$_getFlag()
$_getFlag(name: string): any;Get value from given flag.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
any
Inherited from
$_getRule()
$_getRule(name: string): GetRuleOptions | undefined;Retrieve some rule configuration.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
GetRuleOptions | undefined
Inherited from
$_mapLabels()
$_mapLabels(path: string | string[]): string;Parameters
| Parameter | Type |
|---|---|
path | string | string[] |
Returns
string
Inherited from
$_match()
$_match(
value: any,
state: State,
prefs: ValidationOptions): boolean;Returns true if validations runs fine on given value.
Parameters
| Parameter | Type |
|---|---|
value | any |
state | State |
prefs | ValidationOptions |
Returns
boolean
Inherited from
$_modify()
$_modify(options?: ModifyOptions): Schema;Parameters
| Parameter | Type |
|---|---|
options? | ModifyOptions |
Returns
Inherited from
$_mutateRebuild()
$_mutateRebuild(): this;Resets current schema.
Returns
this
Inherited from
$_mutateRegister()
$_mutateRegister(schema: Schema, options?: MutateRegisterOptions): void;Parameters
| Parameter | Type |
|---|---|
schema | Schema |
options? | MutateRegisterOptions |
Returns
void
Inherited from
SchemaInternals.$_mutateRegister
$_property()
$_property(name: string): any;Get value from given property.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
any
Inherited from
$_reach()
$_reach(path: string[]): Schema;Get schema at given path.
Parameters
| Parameter | Type |
|---|---|
path | string[] |
Returns
Inherited from
$_rootReferences()
$_rootReferences(): any;Get current schema root references.
Returns
any
Inherited from
SchemaInternals.$_rootReferences
$_setFlag()
$_setFlag(
flag: string,
value: any,
options?: SetFlagOptions): void;Set flag to given value.
Parameters
| Parameter | Type |
|---|---|
flag | string |
value | any |
options? | SetFlagOptions |
Returns
void
Inherited from
$_validate()
$_validate(
value: any,
state: State,
prefs: ValidationOptions): ValidationResult;Runs internal validations against given value.
Parameters
| Parameter | Type |
|---|---|
value | any |
state | State |
prefs | ValidationOptions |
Returns
Inherited from
after()
after(limit: Reference | Parseable): this;Validates that the datetime is after the specified limit.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be after (supports keywords) |
Returns
this
The schema instance for method chaining
Examples
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"); // Invalidconst schema = joi.datetime().after("today");
schema.validate(DateTime.now().plus({ days: 1 })); // Valid
schema.validate(DateTime.now().minus({ days: 1 })); // InvalidafterOrEqual()
afterOrEqual(limit: Reference | Parseable): this;Validates that the datetime is after or equal to the specified limit.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be after or equal to |
Returns
this
The schema instance for method chaining
Example
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"); // Invalidallow()
allow(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
alter()
alter(targets: Record<string, (schema: this) => Schema>): this;Parameters
| Parameter | Type |
|---|---|
targets | Record<string, (schema: this) => Schema> |
Returns
this
Inherited from
artifact()
artifact(id: any): this;Parameters
| Parameter | Type |
|---|---|
id | any |
Returns
this
Inherited from
before()
before(limit: Reference | Parseable): this;Validates that the datetime is before the specified limit.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be before (supports keywords) |
Returns
this
The schema instance for method chaining
Examples
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"); // Invalidconst schema = joi.datetime().before("end of month");
schema.validate(DateTime.now().endOf("month").minus({ hours: 1 })); // ValidbeforeOrEqual()
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
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be before or equal to (supports keywords) |
Returns
this
The schema instance for method chaining
Examples
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// '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()
bind(): this;Returns
this
Inherited from
cache()
cache(cache?: Cache): this;Parameters
| Parameter | Type |
|---|---|
cache? | Cache |
Returns
this
Inherited from
cast()
cast(to: "string" | "number" | "object" | "map" | "set"): this;Parameters
| Parameter | Type |
|---|---|
to | "string" | "number" | "object" | "map" | "set" |
Returns
this
Inherited from
concat()
concat(schema: this): this;Parameters
| Parameter | Type |
|---|---|
schema | this |
Returns
this
Inherited from
custom()
custom(fn: CustomValidator, description?: string): this;Parameters
| Parameter | Type |
|---|---|
fn | CustomValidator |
description? | string |
Returns
this
Inherited from
db()
db(connection: any): this;Alias for .knex(). Sets the database connection for database validation rules.
Parameters
| Parameter | Type | Description |
|---|---|---|
connection | any | A Knex instance, transaction, or connection configuration |
Returns
this
Inherited from
default()
default(value?: DefaultableValue): this;Sets a default value if the original value is undefined.
Parameters
| Parameter | Type | Description |
|---|---|---|
value? | DefaultableValue | The 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
const schema = joi.string().default("hello world");
const schemaWithFunction = joi
.number()
.default((parent, helpers) => parent.someOtherField * 2);Inherited from
describe()
describe(): Description;Returns a plain object representing the schema's rules and properties
Returns
Inherited from
description()
description(desc: string): this;Parameters
| Parameter | Type |
|---|---|
desc | string |
Returns
this
Inherited from
disallow()
disallow(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
empty()
empty(schema?: SchemaLike): this;Parameters
| Parameter | Type |
|---|---|
schema? | SchemaLike |
Returns
this
Inherited from
equal()
equal(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
equals()
equals(limit: Reference | Parseable): this;Validates that the datetime is equal to the specified limit. Uses loose equality comparison (==) between DateTime objects.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value to compare against |
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().equals("2023-01-01T00:00:00Z");
schema.validate("2023-01-01T00:00:00.000Z"); // Valid (same moment)error()
error(err:
| Error
| ValidationErrorFunction): this;Parameters
| Parameter | Type |
|---|---|
err | | Error | ValidationErrorFunction |
Returns
this
Inherited from
exactly()
exactly(limit: Reference | Parseable): this;Validates that the datetime is exactly equal to the specified limit. Uses strict equality comparison (===) between DateTime objects.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value to compare against |
Returns
this
The schema instance for method chaining
Example
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"); // Invalidexample()
example(value: any, options?: {
override: boolean;
}): this;Parameters
| Parameter | Type |
|---|---|
value | any |
options? | { override: boolean; } |
options.override? | boolean |
Returns
this
Inherited from
exist()
exist(): this;Returns
this
Inherited from
existsInDb()
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
| Parameter | Type | Description |
|---|---|---|
table | string | Reference | The database table name (can be a Joi reference) |
column | string | Reference | The column name to check (can be a Joi reference) |
options? | DbValidationOptions | Optional configuration: - caseInsensitive: Perform case-insensitive comparison (default: false) - filter: Async function to add additional WHERE clauses to the query |
Returns
this
Example
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
external()
external(method: ExternalValidationFunction, description?: string): this;Parameters
| Parameter | Type |
|---|---|
method | ExternalValidationFunction |
description? | string |
Returns
this
Inherited from
extract()
extract(path: string | string[]): Schema;Returns a sub-schema based on a path of object keys or schema ids.
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | 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
Inherited from
failover()
failover(value: any): this;Parameters
| Parameter | Type |
|---|---|
value | any |
Returns
this
Inherited from
forbidden()
forbidden(): this;Returns
this
Inherited from
fork()
fork(key: string | string[] | string[][], adjuster: SchemaFunction): this;Parameters
| Parameter | Type |
|---|---|
key | string | string[] | string[][] |
adjuster | SchemaFunction |
Returns
this
Inherited from
greater()
greater(limit: Reference | Parseable): this;Validates that the datetime is greater than the specified limit. Alias for after().
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be greater than |
Returns
this
The schema instance for method chaining
id()
id(name?: string): this;Parameters
| Parameter | Type |
|---|---|
name? | string |
Returns
this
Inherited from
invalid()
invalid(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
isAsync()
isAsync(): boolean;Returns a boolean indicating whether this schema contains a rule that requires asynchronous validation.
Returns
boolean
Inherited from
keep()
keep(): this;Returns
this
Inherited from
knex()
knex(connection: any): this;Sets the database connection for database validation rules. This must be called before using .uniqueInDb() or .existsInDb().
Parameters
| Parameter | Type | Description |
|---|---|---|
connection | any | A Knex instance, transaction, or connection configuration |
Returns
this
Example
import knex from 'knex'
const db = knex({ client: 'pg', connection: {...} })
const schema = joi.string().knex(db).uniqueInDb('users', 'email')Inherited from
label()
label(name: string): this;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
this
Inherited from
less()
less(limit: Reference | Parseable): this;Validates that the datetime is less than the specified limit. Alias for before().
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The datetime value that the input must be less than |
Returns
this
The schema instance for method chaining
max()
max(limit: Reference | Parseable): this;Validates that the datetime is less than or equal to the specified limit. Alias for beforeOrEqual().
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The maximum datetime value |
Returns
this
The schema instance for method chaining
message()
message(message: string): this;Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
this
Inherited from
messages()
messages(messages: LanguageMessages): this;Parameters
| Parameter | Type |
|---|---|
messages | LanguageMessages |
Returns
this
Inherited from
meta()
meta(meta: object): this;Parameters
| Parameter | Type |
|---|---|
meta | object |
Returns
this
Inherited from
min()
min(limit: Reference | Parseable): this;Validates that the datetime is greater than or equal to the specified limit. Alias for afterOrEqual().
Parameters
| Parameter | Type | Description |
|---|---|---|
limit | Reference | Parseable | The minimum datetime value |
Returns
this
The schema instance for method chaining
not()
not(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
note()
note(...notes: string[]): this;Parameters
| Parameter | Type |
|---|---|
...notes | string[] |
Returns
this
Inherited from
only()
only(): this;Returns
this
Inherited from
optional()
optional(): this;Returns
this
Inherited from
options()
options(options: ValidationOptions): this;Parameters
| Parameter | Type |
|---|---|
options | ValidationOptions |
Returns
this
Inherited from
preferences()
preferences(options: ValidationOptions): this;Parameters
| Parameter | Type |
|---|---|
options | ValidationOptions |
Returns
this
Inherited from
prefs()
prefs(options: ValidationOptions): this;Parameters
| Parameter | Type |
|---|---|
options | ValidationOptions |
Returns
this
Inherited from
presence()
presence(mode: PresenceMode): this;Parameters
| Parameter | Type |
|---|---|
mode | PresenceMode |
Returns
this
Inherited from
raw()
raw(enabled?: boolean): this;Parameters
| Parameter | Type |
|---|---|
enabled? | boolean |
Returns
this
Inherited from
required()
required(): this;Returns
this
Inherited from
rule()
rule(options: RuleOptions): this;Parameters
| Parameter | Type |
|---|---|
options | RuleOptions |
Returns
this
Inherited from
setLocale()
setLocale(locale: string): this;Sets the locale for the datetime during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
locale | string | The locale code (e.g., 'en-US', 'fr-FR') |
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().setLocale("fr-FR").toLocaleString();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns localized string in FrenchsetZone()
setZone(zone: string | Zone<boolean>, opts?: ZoneOptions): this;Sets the timezone for the datetime during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
zone | string | Zone<boolean> | The timezone to set (IANA timezone name or Luxon Zone object) |
opts? | ZoneOptions | - |
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().setZone("America/New_York");
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns DateTime in Eastern timezoneshared()
shared(ref: Schema): this;Parameters
| Parameter | Type |
|---|---|
ref | Schema |
Returns
this
Inherited from
strict()
strict(isStrict?: boolean): this;Parameters
| Parameter | Type |
|---|---|
isStrict? | boolean |
Returns
this
Inherited from
strip()
strip(enabled?: boolean): this;Parameters
| Parameter | Type |
|---|---|
enabled? | boolean |
Returns
this
Inherited from
tag()
tag(...tags: string[]): this;Parameters
| Parameter | Type |
|---|---|
...tags | string[] |
Returns
this
Inherited from
tailor()
tailor(targets: string | string[]): Schema;Applies any assigned target alterations to a copy of the schema that were applied via any.alter().
Parameters
| Parameter | Type |
|---|---|
targets | string | string[] |
Returns
Inherited from
toBSON()
toBSON(): this;Converts the datetime to BSON format during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toBSON();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: Date object for BSON serializationtoFormat()
toFormat(format: CallbackOrValue<string>): this;Formats the datetime using a custom format string during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
format | CallbackOrValue<string> | The format string (Luxon format tokens) or callback function |
Returns
this
The schema instance for method chaining
Examples
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"const schema = joi
.datetime()
.toFormat((dt, helpers) => (dt.year > 2000 ? "yyyy-MM-dd" : "MM/dd/yy"));toHTTP()
toHTTP(): this;Converts the datetime to HTTP date format during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toHTTP();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "Sat, 15 Jul 2023 15:30:00 GMT"toISO()
toISO(opts?: CallbackOrValue<ToISOTimeOptions>): this;Converts the datetime to ISO 8601 string format during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToISOTimeOptions> | Options for ISO string formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
const schema = joi.datetime().toISO({ suppressMilliseconds: true });
const result = schema.validate("July 15, 2023 3:30 PM");
// Returns: "2023-07-15T15:30:00Z"const schema = joi.datetime().toISO((dt, helpers) => ({
suppressMilliseconds: true,
extendedZone: dt.year > 1970,
precision: "seconds",
}));toISODate()
toISODate(opts?: CallbackOrValue<ToISODateOptions>): this;Converts the datetime to ISO date format (YYYY-MM-DD) during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToISODateOptions> | Options for ISO date formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
const schema = joi.datetime().toISODate();
const result = schema.validate("July 15, 2023 3:30 PM");
// Returns: "2023-07-15"const schema = joi.datetime().toISODate((dt, helpers) => ({
format: dt.year > 2000 ? "extended" : "basic",
}));toISOTime()
toISOTime(opts?: CallbackOrValue<ToISOTimeOptions>): this;Converts the datetime to ISO time format during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToISOTimeOptions> | Options for ISO time formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
const schema = joi.datetime().toISOTime({ suppressMilliseconds: true });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "15:30:00Z"const schema = joi.datetime().toISOTime((dt, helpers) => ({
suppressMilliseconds: dt.millisecond === 0,
}));toISOWeekDate()
toISOWeekDate(): this;Converts the datetime to ISO week date format during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toISOWeekDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-W28-6"toJSDate()
toJSDate(): this;Converts the datetime to a JavaScript Date object during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toJSDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: Date objecttoJSON()
toJSON(): this;Converts the datetime to JSON string format during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toJSON();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-07-15T15:30:00.000Z"toLocal()
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
const schema = joi.datetime().toLocal();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns DateTime in local timezonetoLocalizedString()
toLocalizedString(formatOpts: CallbackOrValue<LocaleOptions>): this;Formats the datetime using locale-specific formatting during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
formatOpts | CallbackOrValue<LocaleOptions> | Locale formatting options or callback function |
Returns
this
The schema instance for method chaining
Examples
const schema = joi
.datetime()
.toLocalizedString({ month: "long", day: "numeric" });
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "July 15" (or localized equivalent)const schema = joi.datetime().toLocalizedString((dt, helpers) => ({
month: dt.month > 6 ? "long" : "short",
day: "numeric",
}));toMillis()
toMillis(): this;Converts the datetime to milliseconds since Unix epoch during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toMillis();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800000toObject()
toObject(opts?: CallbackOrValue<{
includeConfig?: boolean;
}>): this;Converts the datetime to a plain object representation during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<{ includeConfig?: boolean; }> | Options for object conversion or callback function |
Returns
this
The schema instance for method chaining
Examples
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 }const schema = joi.datetime().toObject((dt, helpers) => ({
includeConfig: dt.year > 2000,
}));toRelative()
toRelative(opts?: CallbackOrValue<ToRelativeOptions>): this;Converts the datetime to a relative time string during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToRelativeOptions> | Options for relative time formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
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)const schema = joi.datetime().toRelative((dt, helpers) => ({
base: dt.year > 2020 ? DateTime.now() : DateTime.fromISO("2020-01-01"),
}));toRFC2822()
toRFC2822(): this;Converts the datetime to RFC 2822 format during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toRFC2822();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "Sat, 15 Jul 2023 15:30:00 +0000"toSeconds()
toSeconds(): this;Converts the datetime to seconds since Unix epoch during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toSeconds();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800.0toSQL()
toSQL(opts?: CallbackOrValue<ToSQLOptions>): this;Converts the datetime to SQL datetime format during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToSQLOptions> | Options for SQL formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
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"const schema = joi.datetime().toSQL((dt, helpers) => ({
includeZone: dt.zone.name !== "UTC",
}));toSQLDate()
toSQLDate(): this;Converts the datetime to SQL date format (YYYY-MM-DD) during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toSQLDate();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: "2023-07-15"toSQLTime()
toSQLTime(opts?: CallbackOrValue<ToSQLOptions>): this;Converts the datetime to SQL time format (HH:mm:ss.SSS) during validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
opts? | CallbackOrValue<ToSQLOptions> | Options for SQL time formatting or callback function |
Returns
this
The schema instance for method chaining
Examples
const schema = joi.datetime().toSQLTime({ includeZone: true });
const result = schema.validate("2023-07-15T15:30:45.123Z");
// Returns: "15:30:45.123 Z"const schema = joi.datetime().toSQLTime((dt, helpers) => ({
includeZone: dt.zone.name !== "UTC",
}));toUnixInteger()
toUnixInteger(): this;Converts the datetime to Unix timestamp (seconds as integer) during validation.
Returns
this
The schema instance for method chaining
Example
const schema = joi.datetime().toUnixInteger();
const result = schema.validate("2023-07-15T15:30:00Z");
// Returns: 1689433800toUTC()
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
const schema = joi.datetime().toUTC();
const result = schema.validate("2023-07-15T10:30:00-05:00");
// Returns DateTime in UTC: 2023-07-15T15:30:00ZuniqueInDb()
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
| Parameter | Type | Description |
|---|---|---|
table | string | Reference | The database table name (can be a Joi reference) |
column | string | Reference | The column name to check (can be a Joi reference) |
options? | DbValidationOptions | Optional configuration: - caseInsensitive: Perform case-insensitive comparison (default: false) - filter: Async function to add additional WHERE clauses to the query |
Returns
this
Example
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
unit()
unit(name: string): this;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
this
Inherited from
valid()
valid(...values: any[]): this;Parameters
| Parameter | Type |
|---|---|
...values | any[] |
Returns
this
Inherited from
validate()
validate(value: any, options?: ValidationOptions): ValidationResult<TSchema>;Validates a value using the schema and options.
Parameters
| Parameter | Type |
|---|---|
value | any |
options? | ValidationOptions |
Returns
ValidationResult<TSchema>
Inherited from
validateAsync()
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
| Parameter | Type |
|---|---|
value | any |
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
warn()
warn(): this;Returns
this
Inherited from
warning()
warning(code: string, context: ValidationContext): this;Parameters
| Parameter | Type |
|---|---|
code | string |
context | ValidationContext |
Returns
this
Inherited from
weekday()
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
const schema = joi.datetime().weekday();
schema.validate("2023-07-03T12:00:00Z"); // Valid if Monday
schema.validate("2023-07-01T12:00:00Z"); // Invalid if Saturdayweekend()
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
const schema = joi.datetime().weekend();
schema.validate("2023-07-01T12:00:00Z"); // Valid if Saturday
schema.validate("2023-07-03T12:00:00Z"); // Invalid if Mondaywhen()
Call Signature
when(ref: string | Reference, options:
| WhenOptions<any, any>
| WhenOptions<any, any>[]): this;Parameters
| Parameter | Type |
|---|---|
ref | string | Reference |
options | | WhenOptions<any, any> | WhenOptions<any, any>[] |
Returns
this
Inherited from
Call Signature
when(ref: Schema, options: WhenSchemaOptions): this;Parameters
| Parameter | Type |
|---|---|
ref | Schema |
options | WhenSchemaOptions |
Returns
this