How to validate dates in format MM-DD-YYYY with JavaScript?

Sometimes, we want to validate dates in format MM-DD-YYYY with JavaScript.

In this article, we’ll look at how to validate dates in format MM-DD-YYYY with JavaScript.

How to validate dates in format MM-DD-YYYY with JavaScript?

To validate dates in format MM-DD-YYYY with JavaScript, we can use a regex to get the date parts.

And then we can compare the parts when we put them into the Date constructor to create a new date from them.

For instance, we write:

const isValidDate = (date) => {
  const matches = /^(d{1,2})[-/](d{1,2})[-/](d{4})$/.exec(date);
  if (matches === null) {
    return false;
  }
  const [_, m, d, y] = matches
  const composedDate = new Date(+y, +m - 1, +d);
  return composedDate.getDate() === +d &&
    composedDate.getMonth() === +m - 1 &&
    composedDate.getFullYear() === +y;
}
console.log(isValidDate('10-12-1961'));

We use the /^(d{1,2})[-/](d{1,2})[-/](d{4})$/ regex to extract the date parts with the exec method.

Then we destructure the matches and assign the month to m, day to d, and year to y.

Next, we create a new date object with the Date constructor with the date parts.

We’ve to subtract 1 from m to conform with with the Date constructor accepts as the month value.

Finally, we compare the date, month and year from the composedDate object with the values extracted from the regex.

We use the unary + operator to convert each value to numbers.

Therefore, the console log should log true.

Conclusion

To validate dates in format MM-DD-YYYY with JavaScript, we can use a regex to get the date parts.

And then we can compare the parts when we put them into the Date constructor to create a new date from them.