Tuesday, November 29, 2011

Date Validation using JavaScript

function DateValidation(ObjSrc) {

var d = document.getElementById(ObjSrc.id).value.split('/');
var mm = d[0];
var dd = d[1];
var yy = d[2];
var correct = true;

var todayDate = new Date();
if (mm <= 12)
correct = true;
else {alert("Invalid Date"); return false; }
if ((mm == 1) || (mm == 3) || (mm == 5) || (mm == 7) || (mm == 8) || (mm == 10) || (mm == 12)) {
if (dd <= 31)
correct = true;
else { alert("Invalid Date"); return false; }
}
if ((mm == 4) || (mm == 6) || (mm == 9) || (mm == 11)) {
if (dd <= 30)
correct = true;
else { alert("Invalid Date"); return false; }
}
if (ObjSrc.id == "txtDateOfBirth")
{
if (yy <= (todayDate.getFullYear() - 18)) {

correct = true;
}
else { alert("Invalid Date"); return false; }
if (yy >= (todayDate.getFullYear() - 70))
correct = true;
else { alert("Invalid Date"); return false; }
}
if (ObjSrc.id == "txtDateofJoining") {
if (yy >= (todayDate.getFullYear() - 70))
correct = true;
else { alert("Invalid Date"); return false; }


}

//leap year checking
var leap;
if (yy % 400 == 0 || (yy % 100 != 0 && yy % 4 == 0)) {
leap = 1;

}
else {
leap = 0;

}
if ((leap == 1) && (mm == 2) && (dd <= 29))
correct = true;
if ((leap == 0) && (mm == 2) && (dd <= 28))
correct = true;
if ((leap == 0) && (mm == 2) && (dd >= 28)) {
alert("Invalid Date");
return false;

}
if (correct == true) {

return true;
}
}

No comments:

Post a Comment