SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Member
    Join Date
    Mar 2013
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [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:
    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!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi Ramsz,

    Welcome to the forums

    Something like:

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

    should do the trick.

  3. #3
    SitePoint Member
    Join Date
    Mar 2013
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    YAY! Thanks Also for the quick reply, you rule. And youre the reason ive chosen to stay around at this website and not any other.

    Final solution:


    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);
    			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>

  4. #4
    SitePoint Member
    Join Date
    Mar 2013
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there, im back again. With a problem 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!

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Ramsz View Post
    Hi there, im back again. With a problem The page works fine in all modern browsers, but my client wants it to work in ancient IE7.
    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:
    Code:
    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.

    Code javascript:
    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.

    Code javascript:
    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'));
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    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.

    HTML Code:
    <form id="age_form" action="..." method="post">
    To which I would then remove any inline events, and use scripting to perform those instead.

    Code:
    <input type="submit" id="submit" name="_send_date_" value="Check" onClick="return checkAge()">
    Code javascript:
    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:

    Code javascript:
    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.

    Code javascript:
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    By the way, be very very careful with this code:

    Code:
    theirDate = new Date((year + min_age), month, day);
    The month value ranges from 0 to 11, not from 1 to 12.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •