JavaScript date validation can be done in many ways like month range testing, day range testing (depending on number of days in the month) and so on. Here is shown much simpler solution. Take day, month and year from input string to create JavaScript Date object. Compare input day, month and year with day, month and year extracted from the Date() object. If they aren’t the same then the input date is not valid.
Please try how date validation works (month and day can contain leading zeros):
Enter date (m/d/yyyy): |
Function is checked with JSLint (JavaScript syntax checker and validator).
function isDate(txtDate, separator) { var aoDate, // needed for creating array and object ms, // date in milliseconds month, day, year; // (integer) month, day and year // if separator is not defined then set '/' if (separator === undefined) { separator = '/'; } // split input date to month, day and year aoDate = txtDate.split(separator); // array length should be exactly 3 (no more no less) if (aoDate.length !== 3) { return false; } // define month, day and year from array (expected format is m/d/yyyy) // subtraction will cast variables to integer implicitly month = aoDate[0] - 1; // because months in JS start from 0 day = aoDate[1] - 0; year = aoDate[2] - 0; // test year range if (year < 1000 || year > 3000) { return false; } // convert input date to milliseconds ms = (new Date(year, month, day)).getTime(); // initialize Date() object from milliseconds (reuse aoDate variable) aoDate = new Date(); aoDate.setTime(ms); // compare input date and parts from Date() object // if difference exists then input date is not valid if (aoDate.getFullYear() !== year || aoDate.getMonth() !== month || aoDate.getDate() !== day) { return false; } // date is OK, return true return true; }
isDate() function has an optional second parameter to define date separator. Default value is “/”. In case of other date format (like “d/m/yyyy”) it’s only needed to change the order of day, month and year variables after splitting the input string. The main intention was to keep this function short and simple so support for other date formats has to be done manually. And finally, see how to use date validation. checkDate() function is called on button click “Check the date” above the source code:
function checkDate(){ // define date string to test var txtDate = document.getElementById('txtDate').value; // check date and print message if (isDate(txtDate)) { alert('OK'); } else { alert('Invalid date format!'); } }
You save my life!!
Very great code to rely on .. thanks a lot
Awesome, thanks!
Good One.