How to Validate Date Input in JavaScript
A Date instance can be created in JavaScript by passing the date time string as the parameter in yyyy-mm-dd format as in Date(“2015-01-31”). There’s something important to note here though.
If you pass an invalid date string, the Date instance would still be created. For instance, “2015-02-30” is not a valid date but the Date instance would still be created. The date will however be adjust to point to the next logical date and in this case, our Date will be set as “2015-03-02”.
Thus you’ll have to verify the month, year and day of a Date separately to detect an invalid date. A regex is not enough.
function isValidDate(str) {
// mm-dd-yyyy hh:mm:ss
var regex = /(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\s*(\d{0,2}):?(\d{0,2}):?(\d{0,2})/,
parts = regex.exec(str);
if (parts) {
var date = new Date(+parts[3], +parts[1] - 1, +parts[2], +parts[4], +parts[5], +parts[6]);
if (date.getDate() == parts[2] && date.getMonth() == parts[1] - 1 && date.getFullYear() == parts[3]) {
return date;
}
}
return false;
}
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory