dateLast updated on
Last updated on
Validate date strings
Validate date strings in ISO 8601 format (YYYY-MM-DD). The Date primitive ensures dates are properly formatted and represent valid calendar dates.
Examples
Creating dates
// Direct validation
const date = open.date('2024-01-15')
// Parse unknown input
const date = open.date.parse(jsonData)
// Check validity without throwing
if (open.date.isValid('2024-02-29')) {
console.log('Valid leap year date')
}Parsing external data
// Parse unknown input (throws on error)
const date = open.date.parse(userInput)
// Safe parsing (returns result object)
const result = open.date.safeParse(userInput)
if (result.success) {
console.log(`Date: ${result.data}`)
} else {
console.error(result.error.message)
}Using with forms
const form = open.form({
name: 'booking',
fields: {
checkIn: { type: 'date', label: 'Check-in Date' },
checkOut: { type: 'date', label: 'Check-out Date' }
}
})
const filled = form.fill({
fields: {
checkIn: open.date('2024-06-01'),
checkOut: open.date('2024-06-07')
}
})API
Direct Call
open.date(input: string): stringPass a date string for validation. Returns the validated string or throws on error.
const date = open.date('2024-01-15')Static Methods
parse: (input: unknown) => string
Parse unknown input (throws on error)
safeParse: (input: unknown) => Result<string>
Parse unknown input (returns result object)
isValid: (input: string) => boolean
Check if a string is a valid date
Format
The Date primitive expects and returns strings in ISO 8601 date format:
YYYY-MM-DD| Component | Description | Range |
|---|---|---|
YYYY | Four-digit year | 0000-9999 |
MM | Two-digit month | 01-12 |
DD | Two-digit day | 01-31 |
Validation
The Date primitive validates:
- String must match
YYYY-MM-DDformat exactly - Year, month, and day must be valid numbers
- Day must be valid for the given month (accounts for leap years)
// Valid
open.date('2024-01-15')
open.date('2024-02-29') // Leap year
open.date('2000-12-31')
// Invalid - throws Error
open.date('2024-1-15')
// Error: Invalid Date: must be in YYYY-MM-DD format
open.date('2024-13-01')
// Error: Invalid Date: month must be between 01 and 12
open.date('2024-02-30')
// Error: Invalid Date: invalid day for month
open.date('2023-02-29') // Not a leap year
// Error: Invalid Date: invalid day for month
open.date('not-a-date')
// Error: Invalid Date: must be in YYYY-MM-DD formatRelated
- Primitives Overview - All available primitives
- Datetime - Date with time component
- Time - Time only
- Date Field - Date field type