How to Check for Invalid Dates in TypeScript?

Have you ever seen your app behave strangely just because someone entered the wrong date? For example, a user might type “2025-02-30”, which is not even a real date or the used date format is not valid for the app’s date settings. These small issues can cause big problems if we don’t handle them properly.

In this tutorial, I’ll explain how to check for invalid dates in TypeScript. We’ll use the Date object and the isNaN function to find out if a date is valid or not. I’ll also show how to manage different date formats like “DD/MM/YYYY” or “MM/DD/YYYY”, and how to handle special cases like leap years.

Understanding the Date Object in TypeScript

In TypeScript, the Date object represents a single moment in time. It provides methods to work with dates and times, such as retrieving the current date, manipulating dates, and formatting date strings. However, when dealing with user input or external data sources, it’s crucial to validate the dates to ensure data integrity and avoid potential errors.

Check out:  Create a Date from Year, Month, and Day in TypeScript

Checking for Invalid Dates

To check if a date is valid in TypeScript, you can utilize the Date object and the isNaN function. Here’s how you can accomplish this:

  1. Create a Date object from the input string using the Date constructor.
  2. Use the getTime() method to retrieve the timestamp of the Date object.
  3. Pass the timestamp to the isNaN() function to determine if the date is valid or not.

Let’s consider an example scenario. Suppose you are developing a web application for a US-based company that requires users to enter their date of birth. Here’s how you can validate the user input:

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

// Example usage
const userInput = "1990-05-15";
if (isValidDate(userInput)) {
  console.log("Valid date");
} else {
  console.log("Invalid date");
}

Output:

Check invalid dates in typescript

In this example, the isValidDate function takes a date string as input and returns true If the date is valid, it is true; otherwise, it is false. It creates a new Date object using the input string and then checks if the timestamp obtained from getTime() is a valid number using isNaN(). If the timestamp is not a valid number, it means the date is invalid.

Handling Different Date Formats

One challenge when validating dates is handling different date formats. Depending on the requirements of your application, you may need to support various formats such as “YYYY-MM-DD”, “MM/DD/YYYY”, or “DD/MM/YYYY”. To accommodate different formats, you can use regular expressions or parsing libraries like date-fns or Moment.js.

Here’s an example of how you can validate a date string in the “MM/DD/YYYY” format using a regular expression:

Check out: Add Months to a Date in TypeScript

function isValidUSDate(dateString: string): boolean {
  const pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
  if (!pattern.test(dateString)) {
    return false;
  }
  const [_, month, day, year] = dateString.match(pattern)!;
  const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
  return (
    date.getMonth() === parseInt(month) - 1 &&
    date.getDate() === parseInt(day) &&
    date.getFullYear() === parseInt(year)
  );
}

// Example usage
const userInput = "05/12/2025";
if (isValidUSDate(userInput)) {
  console.log("Valid US date");
} else {
  console.log("Invalid US date");
}

Output:

Validate date value in Typescript

In this example, the isValidUSDate function first checks if the input string matches the expected format using a regular expression. If the format is correct, it extracts the month, day, and year components from the matched groups. It then creates a new Date object using the extracted values and compares them with the original components to ensure the date is valid.

Check out: Get the Current Date in TypeScript

Handling Leap Years and Edge Cases

When validating dates, it’s important to consider leap years and edge cases. Leap years have an extra day in February, which can affect the validity of certain dates. Additionally, there are edge cases like “2025-02-30” that should be considered invalid.

To handle leap years, you can use the built-in Date object’s behavior. The Date constructor automatically adjusts the date if the provided values are out of range. For example, “2024-02-30” will be adjusted to “2024-03-01”. You can leverage this behavior to check if the adjusted date matches the original input.

Here’s an example that demonstrates handling leap years and edge cases:

function isValidDate(dateString: string): boolean {
  const [year, month, day] = dateString.split("-").map(Number);
  
  // Create a Date object using the year, month (zero-based), and day
  const date = new Date(year, month - 1, day);
  
  // Validate the constructed date object
  return (
    date.getFullYear() === year &&
    date.getMonth() === month - 1 &&
    date.getDate() === day
  );
}

// Example usage
const leapYearDate = "2024-02-29";
const invalidDate = "2024-02-30";

console.log(isValidDate(leapYearDate)); // true
console.log(isValidDate(invalidDate)); // false

Output:

Validate the date values in Typescript

In this example, the isValidDate function creates a Date object from the input string and then compares the year, month, and day components with the original input values. If the adjusted date matches the original input, it means the date is valid, taking into account leap years and edge cases.

I hope you understand the importance of date validation and that this tutorial has given you a clear, comprehensive approach to handling invalid dates in TypeScript. By applying these methods, you’ll enhance the robustness of your data-related operations in any project.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.