isValidDate
Checks if a value is a valid Date object.
1/**
2 * Checks if a value is a valid Date object.
3 *
4 * @param value - The value to check.
5 * @returns True if the value is a Date and represents a valid date.
6 */
7export function isValidDate(value: any): boolean {
8 return value instanceof Date && !isNaN(value.getTime());
9}
Accurate Date Validation
Confirms that the value is a
Date
instance and represents a valid date (notInvalid Date
).Safe Type Checking
Uses
instanceof Date
to ensure the value is genuinely a Date object, avoiding false positives from strings or numbers.Handles Edge Cases
Rejects malformed or
NaN
-based dates that technically pass asDate
objects but are invalid.Lightweight and Reliable
Compact logic with no dependencies makes it ideal for frequent use in validations and type guards.
Tests | Examples
1test('isValidDate - valid date', () => {
2 expect(isValidDate(new Date())).toBe(true);
3});
4
5test('isValidDate - invalid date', () => {
6 expect(isValidDate(new Date('invalid'))).toBe(false);
7});
8
9test('isValidDate - string instead of Date', () => {
10 expect(isValidDate('2023-01-01')).toBe(false);
11});
12
13test('isValidDate - number instead of Date', () => {
14 expect(isValidDate(Date.now())).toBe(false);
15});
16
17test('isValidDate - null and undefined', () => {
18 expect(isValidDate(null)).toBe(false);
19 expect(isValidDate(undefined)).toBe(false);
20});
21
22test('isValidDate - plain object', () => {
23 expect(isValidDate({})).toBe(false);
24});
Common Use Cases
Form Input Validation
Validate date fields from user input or forms before processing or submitting.
Data Parsing and Importing
Ensure date values parsed from CSV, JSON, or external sources are valid before use.
API Payload Validation
Check incoming date fields in API requests to prevent runtime errors or invalid database entries.
Conditional Logic Based on Time
Guard time-sensitive logic (e.g., scheduling, expiration) with reliable date validation.
Testing and Assertion Utilities
Confirm that test results or mock data contain valid date values when asserting correctness.