/ Published in: JavaScript
Find the date with or without a year and with double or single digit month or day. Easily extendable to other date delimiters and formats.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Validates date inputs function isDate(dateStr, testYear) { var dateObj; var dateStamp; var day; var month; var year; var dateRegex; // Set regex pattern based to test for year or not. if(testYear === undefined || testYear == true) { testYear = true; dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/.exec(dateStr); } else { testYear = false; dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})$/.exec(dateStr); } // Validate string. if(dateRegex == null) { return false; } // Get day, month, and year if testYear selected (or by default). month = parseInt(dateRegex[0]) - 1; // Subtract 1 because JS dates are 0-11. day = parseInt(dateRegex[1]); if(testYear) { year = parseInt(dateRegex[2]); } else { year = 1999; // This is arbitrary so long as it isn't a leap year. } // Create dateObj. dateStamp = (new Date(year, month, day)).getTime(); dateObj = new Date(); dateObj.setTime(dateStamp); // Validate date. if (dateObj.getMonth() !== month || dateObj.getDate() !== day || dateObj.getYear() !== year) { return false; } return true; }