Click to See Complete Forum and Search --> : Age Validation


Geat
02-14-2003, 08:24 AM
I've got a date in three pieces: the day, month and year as individual items.

I need to verify that the person whose DOB it is is between 18 and 31 years (i.e. the time between the DOB and today's date lies within that range).

Any quick fixes?

gil davis
02-14-2003, 08:29 AM
<script>
var mo = 8; // September
var dy = 9;
var yr = 1984;
var then = new Date(yr, mo, dy);
var now = new Date();
var age = (now - then) / (1000 * 60 * 60 * 24 * 365);
alert(age);
</script>

Geat
02-14-2003, 08:34 AM
That's great, but the month is selected from a dropdown list as a string "January" etc.

I could code an array with each string corresponding to a numerical equivalent, but is there a more elegant way - or can I find the index of the selected item in the month combo?

gil davis
02-14-2003, 08:52 AM
Originally posted by Geat
can I find the index of the selected item in the month combo?
document.formName.selectName.selectedIndex

Remember that the index of the first option in a select is zero. For example:

<form>
<select onchange="alert(this.selectedIndex)">
<option>-- Please select a month --
<option>January
...
</select>
</form>

If "January" is selected, then selectedIndex will be 1. If no option is selected, some browsers will return -1 for the selectedIndex. To be safe, you can change the dummy option to:

<option selected>-- Please select a month --

Geat
02-14-2003, 08:55 AM
Just like VB then, sorted.

It's okay - I force the list to default to January, so there'll be no problem there...

Thanks a lot, you've helped again!

gil davis
02-14-2003, 09:46 AM
I made a more complete example using a drop-down for the month and day that is leap-year sensitive. Maybe you can use it.

http://home.att.net/~gil.davis/age.htm

Geat
02-14-2003, 10:14 AM
That's really good mate - and saves a lame client side check when the user submits the form. Cheers!