function isValidDate(txtDate) {
var objDate; // date object initialized from the txtDate string
var mSeconds; // milliseconds from txtDate
// date length should be 10 characters - no more, no less
if (txtDate.length != 10) return false;
// extract day, month and year from the txtDate string
// expected format is YYYY-mm-DD
// subtraction will cast variables to integer implicitly
var day = txtDate.substring(8,10) - 0;
var month = txtDate.substring(5,7) - 1; // because months in JS start with 0
var year = txtDate.substring(0,4) - 0;
// third and sixth character should be /
if (txtDate.substring(2,3) != '-') return false;
if (txtDate.substring(5,6) != '-') return false;
// test year range
if (year < 999 || year > 3000) return false;
// convert txtDate to the milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// set the date object from milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// if there exists difference then date isn't valid
if (objDate.getFullYear() != year) return false;
if (objDate.getMonth() != month) return false;
if (objDate.getDate() != day) return false;
// otherwise return true
return true;
}
Search This Blog
Wednesday, January 5, 2011
Date validation Java Script
Labels:
javascript
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment