lotterygirl
asked on
Check Age Javascript function
I have a javascript function that checks to see if the person is over 18 according to the date of birth they entered in a text box. My problem is that today's date is 3/28/2006 and if they enter a birthdate greater then 2/1/9888 it doesn't show them as 18. In case I didn't say it right that means that if they enter 2/1/1988 it doesn't pop up the under 18 message. If they enter 2/2/1988 it does pop up the under 18 message. Anyone born on or before 3/28/1988 should pass the over 18 test. Can you tell what I'm doing wrong or have a better suggestion on how to write this function?
function CheckAge(objField)
{
var regexp = /\d{2}\/\d{2}\/\d{4}/;
if(!objField.value.match(r egexp)){
alert('Invalid date - format : MM/DD/YYYY');
return;
}
var day = objField.value.substr(3,2) ;
var month = objField.value.substr(0,2) ;
var year = objField.value.substr(6,4) ;
var d = new Date();
var age = d.getYear() - year;
if(d.getMonth()/1 < month){
age--;
}else if(d.getMonth()/1==month && d.getDay()/1<=day){
age--;
}
if (age < 18)
// if under 18 display message
{
alert("You must be at least 18 years of age.");
objField.focus();
objField.select();
return false;
}
return true;
}
Thanks
function CheckAge(objField)
{
var regexp = /\d{2}\/\d{2}\/\d{4}/;
if(!objField.value.match(r
alert('Invalid date - format : MM/DD/YYYY');
return;
}
var day = objField.value.substr(3,2)
var month = objField.value.substr(0,2)
var year = objField.value.substr(6,4)
var d = new Date();
var age = d.getYear() - year;
if(d.getMonth()/1 < month){
age--;
}else if(d.getMonth()/1==month && d.getDay()/1<=day){
age--;
}
if (age < 18)
// if under 18 display message
{
alert("You must be at least 18 years of age.");
objField.focus();
objField.select();
return false;
}
return true;
}
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks dakyd. That worked perfectly.
var today = new Date();
var myDate = new Date();
myDate.setFullYear(1988,1,
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var ONE_YEAR = ONE_DAY * 365;
var date1_ms = today.getTime()
var date2_ms = myDate.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
alert(Math.floor(differenc
(1988,1,2); = Year,Month,Day (and month is 0-11)