[simple] Age checker, neem to make it check for day and month (mandatory)

Hi there, Ive got the following problem with a code ive come across.

Code:


	<script language="javascript">
		function checkAge()
		{
			/* the minumum age you want to allow in */
			var min_age = 16;

			/* change "age_form" to whatever your form has for a name="..." */
			var year = parseInt(document.forms["age_form"]["year"].value);
			var month = parseInt(document.forms["age_form"]["month"].value) - 1;
			var day = parseInt(document.forms["age_form"]["day"].value);

			var theirDate = new Date((year + min_age), month, day);
			var today = new Date;
			
			
			if ( (today.getTime() - theirDate.getTime()) < 0) {
				alert("Youre too young!");
				return false;
			}
			else {
				return true;
			}
		}
	</script>

This code above works, and when submitted the form, it checks the age for the minimum of 16. As you can see.

Ive got a problem that it doesnt look at the days / month given.
Default the list is set at a value of 00.

I would like to add some additional JS code to check if the day and month have been given.
If not given. An alert box popup with a message will be displayed.

How would be that be achieved? Any advice is more than welcome since im a JS noob. Thanks!

Hi Ramsz,

Welcome to the forums :slight_smile:

Something like:

if (year == 0 || month == 0 || day == 0){
  alert("Please enter something sensible");
}

should do the trick.

YAY! Thanks :smiley: Also for the quick reply, you rule. And youre the reason ive chosen to stay around at this website and not any other. :wink:

Final solution:

	<script language="javascript">
		function checkAge()
		{
			/* the minumum age you want to allow in */
			var min_age = 16;

			/* change "age_form" to whatever your form has for a name="..." */
			var year = parseInt(document.forms["age_form"]["year"].value);
			var month = parseInt(document.forms["age_form"]["month"].value);
			var day = parseInt(document.forms["age_form"]["day"].value);

			var theirDate = new Date((year + min_age), month, day);
			var today = new Date;
			
			if (month == 0){
			  alert("..and your month is?");
			  return false;
			}
			if (day == 0){
			  alert("Your birthday is still missing!");
			  return false;
			}
			if ( (today.getTime() - theirDate.getTime()) < 0) {
				alert("Youre too young, to visit us.");
				return false;
			}
			else {
				return true;
			}
		}
	</script>

Hi there, im back again. With a problem :frowning: The page works fine in all modern browsers, but my client wants it to work in ancient IE7.

How could this be achieved? Currently it doesnt check, you press check and it just moves on to the website. Without checking the age.

My final code, of the entire index page, can be see here: http://pastebin.com/ZW9eV4T7

Thanks!

The problem is happening because you are attempting to access the SELECT element incorrectly. It has no value property. Modern web browsers set the value property, but not IE7 or earlier.

To correctly access the select value, means getting the selectedIndex of the field, and using that number to access the options array, so that you can get the text of that option.

The long way of doing that is with:

var year = parseInt(document.forms["age_form"]["year"].options[document.forms["age_form"]["year"].selectedIndex].text)

A better way is to save the year field to a variable, so that you can more easily make use of it.


var yearField = document.forms["age_form"]["year"],
    year = parseInt(yearField.options[yearField.selectedIndex].text),
    monthField = document.forms["age_form"]["month"],
    month = parseInt(monthField.options[monthField.selectedIndex].text),
    dayField = document.forms["age_form"]["day"],
    day = parseInt(dayField.options[dayyearField.selectedIndex].text);

And even better, is to reduce the amount of duplication, and use a function to get the selected value.


function getSelectedValue(form, fieldName) {
    var field = document.forms[form][fieldName];
    return field.options[field.selectedIndex].text;
}

var year = parseInt(getSelectedValue('age_form', 'year')),
    month = parseInt(getSelectedValue('age_form', 'month')),
    day = parseInt(getSelectedValue('age_form', 'day'));

Further on from here, I would fix some things up, by moving the script out of the head and to the end of the body instead.

Then, I would fix how the form is being accessed, because the name attribute should only be used for naming form fields. The form itself should be identified by an id attribute instead.

<form id="age_form" action="..." method="post">

To which I would then remove any inline events, and use scripting to perform those instead.

<input type="submit" [color="red"][s]id="submit"[/s][/color] name="_send_date_" value="Check" [color="red"][s]onClick="return checkAge()"[/s][/color]>

document.getElementById('age_form').onsubmit = checkAge;

Which will then allow me to access the form more correctly, by using and object that refers directly to the form itself, instead of just some text:


function getSelectedValue(form, fieldName) {
    var field = form.elements[fieldName];
    return field.options[field.selectedIndex].text;
}

How do we get that direct reference to the form? We can do that quite easily by making good use of the this keyword, which refers to the element that the scripting event was assigned to.


function checkAge() {
    var form = this, // The this keyword refers directly to the form, when scripting is used to assign the event function
        min_age = 16,
        year = parseInt(getSelectedValue(form, 'year')),
        month = parseInt(getSelectedValue(form, 'month')),
        day = parseInt(getSelectedValue(form, 'day')), 
        ...     

But that’s just matters of style, which help to make things more flexible for yourself when later maintenance occurs.

The important thing is that you understand why the initial code wasn’t working, and how to fix things.

By the way, be very very careful with this code:

theirDate = new Date((year + min_age), month, day);

The month value ranges from 0 to 11, not from 1 to 12.