SCHEMA
Validation Methods
.date
Introduction

Schema - Date

The .date method is used to validate whether a given value is a valid date in a specified format. It supports multiple date formats, including DD-MM-YYYY, DD/MM/YYYY, ISO8601, and more. This method is particularly useful for ensuring date consistency in your application.


Supported Formats

FormatDescription
DD-MM-YYYYDay-Month-Year format with dashes (-).
DD/MM/YYYYDay-Month-Year format with slashes (/).
MM-DD-YYYYMonth-Day-Year format with dashes (-).
MM/DD/YYYYMonth-Day-Year format with slashes (/).
YYYY-MM-DDISO standard Year-Month-Day with dashes (-).
YYYY/MM/DDYear-Month-Day format with slashes (/).
ISO8601ISO 8601 format (e.g., 2023-01-01T00:00:00Z).

Example: Basic Date Validation

Below is an example of how to use .date to validate whether a value is a valid date in the specified format:

import { schema } from "vkrun"
 
// Validate DD-MM-YYYY format
const schemaDDMMYYYY = schema().date("DD-MM-YYYY")
 
const validateA = schemaDDMMYYYY.validate("30-12-2000") // true
const validateB = schemaDDMMYYYY.validate("12-30-2000") // false
 
console.log(validateA) // true
console.log(validateB) // false

Example: Using ISO 8601 Format

The .date method also supports ISO 8601 dates for strict validation.

const schemaISO = schema().date("ISO8601")
 
const validateC = schemaISO.validate(new Date().toISOString()) // true
const validateD = schemaISO.validate("30-12-2000") // false
 
console.log(validateC) // true
console.log(validateD) // false

Async Example: Validating Date from a Promise

The .date method works seamlessly with async validations for scenarios where the date is returned from an API or database.

const value = async (): Promise<string> => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("30-12-2000"), 100)
  })
}
 
const schemaAsync = schema().date("DD-MM-YYYY")
 
schemaAsync.validateAsync(value()).then(console.log) // true
Copyright © 2024 - 2025 MIT by Mario Elvio