How to validate date with format "mm/dd/yyyy" in JavaScript?

I want to validate the date format on an input using the format mm/dd/yyyy.

I found the code below on a site and tried using it, but it doesn’t seem to work correctly:

function isDate(ExpiryDate) { var objDate, mSeconds, day, month, year;

if (ExpiryDate.length !== 10) return false;

if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') return false;

month = ExpiryDate.substring(0, 2) - 1;
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;

if (year < 1000 || year > 3000) return false;

mSeconds = (new Date(year, month, day)).getTime();
objDate = new Date();
objDate.setTime(mSeconds);

if (objDate.getFullYear() !== year || objDate.getMonth() !== month || objDate.getDate() !== day) return false;

return true;

}

function checkDate(){ var ExpiryDate = document.getElementById(’ ExpiryDate’).value; if (isDate(ExpiryDate)) { alert(‘OK’); } else { alert(‘Invalid date format!’); } }

Can anyone suggest what might be wrong or offer a better approach to validate this format? Also, while working on this I was doing something similar with javascript array intersection, and it got me thinking there must be a more reliable pattern for validation too.

Hey, you’re very close! One subtle thing I noticed is that space inside getElementById(' ExpiryDate'). That extra space means the script can’t actually find the input element, so it never gets the date value. Just remove the space—change it to 'ExpiryDate'—and that part should work fine. From my experience with javascript validate dates and other input issues, clean input references save a ton of debugging headaches later on!

Building on that, the logic you have is solid, but like Priyada mentioned, watch out for that space in the ID string. Also, a little trick I use when I do javascript validate dates is to add a quick regex upfront to catch the obvious format errors before parsing the date. Something like:

/^\d{2}\/\d{2}\/\d{4}$/

This pattern ensures the date looks like mm/dd/yyyy right away. It’s a neat filter that keeps the process clean. I use this method a lot—similar to how I handle javascript array intersection—validate the shape first, then do the detailed logic.

I totally relate-spent hours on this exact problem, mostly because of a sneaky leading space in the ID string! Beyond that, trimming whitespace from the user input is a great habit before running any checks, especially when you do javascript validate dates. What really helped me was combining the regex check with your Date object validation. This double layer makes sure you catch formatting issues and invalid dates (like 02/30/2023). Interestingly, it’s the same principle I apply in javascript array intersection: sanitize and structure data upfront, and everything else just falls into place more smoothly.