How to Check If Date is Valid in Typescript?

As a JavaScript/Typescript developer, I often encounter the need to validate dates, especially when working with user inputs or data from various sources. In this tutorial, I will explain different methods to check if a date is valid in TypeScript.

To check if a date is valid in TypeScript, you can use the Date object and isNaN function. Create a Date object from the input string and use the getTime method. If getTime returns NaN, the date is invalid. This method is simple yet effective for basic date validation in TypeScript applications.

Check If Date is Valid in Typescript

Date validation is crucial in many applications, from booking systems to data analysis tools. TypeScript enhances JavaScript’s handling of dates by allowing us to enforce type safety and reduce runtime errors.

Let us look at various methods to check if date is valid in Typescript.

1. Using Date Object and isNaN

The Date object in JavaScript (and, by extension, TypeScript) is the go-to way to handle dates. However, not all date strings create valid Date objects. Here’s a straightforward way to check if a date is valid in Typescript.

function isValidDate(dateString: string): boolean {
    const date = new Date(dateString);
    return !isNaN(date.getTime());
}

// Usage
console.log(isValidDate("2024-04-45"));
console.log(isValidDate("2024-04-28"));

This function attempts to create a Date object from the input string. It then uses the getTime method, which returns the number of milliseconds since January 1, 1970. If the date is invalid, getTime returns NaN, which we check using isNaN.

See also  this Keyword in Typescript

You can check the screenshot below:

typescript check if date is valid

2. Regular Expressions for Format Validation

You can also use regular expressions for date validations. Here is a complete code.

function isValidDate(dateString: string): boolean {
    const date = new Date(dateString);
    return !isNaN(date.getTime());
}

function isValidFormattedDate(dateString: string): boolean {
    const regex = /^\d{4}-\d{2}-\d{2}$/; // Adjust regex according to your format
    return regex.test(dateString) && isValidDate(dateString);
}

// Usage
console.log(isValidFormattedDate("2024-02-28")); 
console.log(isValidFormattedDate("02-28-2024"));

This method first checks if the date string matches a specific format (here, YYYY-MM-DD) before checking its validity.

You can see the output in the screenshot below.

Check If Date is Valid in Typescript

3. Using TypeScript Type Guards

You can also leverage Typescript type guards to check if a date is valid in Typescript.

function isDate(object: any): object is Date {
    return object instanceof Date && !isNaN(object.getTime());
}

// Usage
const maybeDate = new Date("2024-02-15");
if (isDate(maybeDate)) {
    console.log("Valid date");
} else {
    console.log("Invalid date");
}

Once you run the code using VS code, you can see the output like the screenshot below.

typescript check date is valid

Conclusion

Validating dates is a common requirement in web development. TypeScript, with its strong typing system, offers various ways to ensure you’re working with valid dates. Whether through simple Date object checks, regular expressions for format validation, or utilizing type guards for more complex scenarios. I hope you know how to check if a date is valid in Typescript.

You may also like:

>