Friday, July 1, 2011

JavaScript date validation

JavaScript JavaScript date validation can be done in many ways, like month range testing, then day range testing (depend on month) and so on. I suggest simpler solution. Take day, month and year from string to create a Date object. Compare day, month and year with day, month and year extracted from the Date() object.

If they aren't the same, than the input date is not valid. Please try how date validation works:
Enter date (mm/dd/yyyy): /* Function is checked with JSLint (JavaScript syntax checker and validator).
function isDate(txtDate) {
var objDate, // date object initialized from the txtDate string mSeconds, // txtDate in milliseconds day, // day month, // month year; // year // date length should be 10 characters (no more no less)
if (txtDate.length !== 10) { return false; } // third and sixth character should be '/'
if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/')
{ return false; } // extract month, day and year from the txtDate
(expected format is mm/dd/yyyy) // subtraction will cast variables to integer implicitly (needed // for !== comparing)
month = txtDate.substring(0, 2) - 1; // because months in JS start from 0
day = txtDate.substring(3, 5) - 0;
year = txtDate.substring(6, 10) - 0; // test year range
if (year < 1000 || year > 3000) { return false; } // convert txtDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime(); // initialize Date() object from calculated milliseconds objDate = new Date(); objDate.setTime(mSeconds); // compare input date and parts from Date() object // if difference exists then date isn't valid
if (objDate.getFullYear() !== year || objDate.getMonth() !== month || objDate.getDate() !== day)
{ return false; } // otherwise return true return true; }
 And finally, see how to use date validation function. checkDate() is called on button click. 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!'); } } */ This entry was posted on January 23, 2009 and is filed under JavaScript

No comments:

Post a Comment