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
Format | Description |
---|---|
DD-MM-YYYY | Day-Month-Year format with dashes (- ). |
DD/MM/YYYY | Day-Month-Year format with slashes (/ ). |
MM-DD-YYYY | Month-Day-Year format with dashes (- ). |
MM/DD/YYYY | Month-Day-Year format with slashes (/ ). |
YYYY-MM-DD | ISO standard Year-Month-Day with dashes (- ). |
YYYY/MM/DD | Year-Month-Day format with slashes (/ ). |
ISO8601 | ISO 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