Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Trying to compare value of option input box and if age under 18 "error message"

    Hi

    the section of code for Interest and Age need to be compared to see if

    option 2 is chosen and if age under 18 they cannot purchase Option 2 (Adult Books).

    This part of the code is not working.

    I would very much appreciate some help




    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <html>
    <head>
    <title>home</title>
    <link href="mystyles.css" rel="stylesheet" type="text/css"/>



    <script type="text/javascript" src="date_time.js"></script>
    <script>

    function validateForm(){

    var x = document.forms["myForm"]["lastname"].value;
    x = x.replace(/^\s+/,""); // strip leading spaces
    x1 = x.replace(/[^a-z]/gi,""); // strip non-alpha chars
    if ((/[^a-z\s&'-\.]/gi.test(x)) || (x.length == 0) || (x1.length < 2)) {
    alert ("Last name must be filled out - only alpha characters (2 minimum), space, apostrophe, hyphen, full stop and & are valid in this field");
    myForm.lastname.focus();
    return false;
    }

    var x = document.forms["myForm"]["firstname"].value;
    x = x.replace(/^\s+/,""); // strip leading spaces
    x1 = x.replace(/[^a-z]/gi,""); // strip non-alpha chars
    if ((/[^a-z\s&'-\.]/gi.test(x)) || (x.length == 0) || (x1.length < 2)) {
    alert ("First name must be filled out - only alpha characters (2 minimum), space, apostrophe, hyphen, full stop and & are valid in this field");
    myForm.firstname.focus();
    return false;
    }

    var x=document.forms["myForm"]["address"].value
    if (x==null || x==""){
    alert("Address must be filled out");
    myForm.address.focus();
    return false;
    }

    var x=document.forms["myForm"]["suburb"].value
    if (x==null || x==""){
    alert("Suburb must be filled out");
    myForm.suburb.focus();
    return false;
    }

    ErrorText= "";
    if ( document.myForm.state.selectedIndex == 0 ) {
    alert ( "Please select your State." );
    myForm.state.focus();
    return false;
    }
    if (ErrorText= "") {
    form.submit();
    }

    var x=document.forms["myForm"]["postcode"].value
    if (x==null || x==""){
    alert("Postcode must be filled out")
    myForm.postcode.focus();
    return false;
    }

    if (!IsNumeric(x)){
    alert("Please enter only numbers in the Postcode field")
    return false;
    }


    var x=document.forms["myForm"]["cphone"].value
    if (x==null || x=="") {
    alert("Contact Phone must be filled out")
    myForm.cphone.focus();
    return false;
    }

    if (!IsNumeric(x)) {
    alert("Please enter only numbers in the Contact Phone field")
    myForm.cphone.focus();
    return false;
    }


    var x=document.forms["myForm"]["email"].value
    if (x==null || x==""){
    alert("Email must be filled out");
    myForm.email.focus();
    return false;
    } else {
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
    alert("Not a valid e-mail address");
    myForm.email.focus();
    return false;
    }
    }

    var x=document.forms["myForm"]["interest"].value
    if (x==null || x==""){
    alert("Please select an interest");
    myForm.interest.focus();
    return false;
    }

    var x=document.forms["myForm"]["field"].value
    if (x==null || x==""){
    alert("Please fill out your Date of Birth in the requested format")
    myForm.field.focus();
    return false;
    }

    if (!ageCount()){
    alert("Please fill out your Date of Birth in the requested format")
    myForm.field.focus();
    return false;
    }


    }

    </script>

    <script>
    function check_date(field)
    {
    var checkstr = "0123456789";
    var DateField = field;
    var Datevalue = "";
    var DateTemp = "";
    var seperator = "/";
    var day;
    var month;
    var year;
    var leap = 0;
    var err = 0;
    var i;

    var retValue = true;

    err = 0;
    DateValue = DateField//.value;


    /* Delete all chars except 0..9 */
    for (i = 0; i < DateValue.length; i++) {
    if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
    DateTemp = DateTemp + DateValue.substr(i,1);
    }
    }
    DateValue = DateTemp;
    /* Always change date to 8 digits - string*/
    /* if year is entered as 2-digit / always assume 20xx */


    if (DateValue.length == 6) {
    DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
    if (DateValue.length != 8) {
    err = 19;}
    /* year is wrong if year = 0000 */
    year = DateValue.substr(4,4);
    if (year == 0) {
    err = 20;
    }
    /* Validation of month*/
    month = DateValue.substr(2,2);
    if ((month < 1) || (month > 12)) {
    err = 21;
    }
    /* Validation of day*/
    day = DateValue.substr(0,2);
    if (day < 1) {
    err = 22;
    }
    /* Validation leap-year / february / day */
    if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
    leap = 1;
    }
    if ((month == 2) && (leap == 1) && (day > 29)) {
    err = 23;
    }
    if ((month == 2) && (leap != 1) && (day > 28)) {
    err = 24;
    }
    /* Validation of other months */
    if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
    err = 25;
    }
    if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
    err = 26;
    }
    /* if 00 ist entered, no error, deleting the entry */
    if ((day == 0) && (month == 0) && (year == 00)) {
    err = 0; day = ""; month = ""; year = ""; seperator = "";
    }
    /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
    if (err == 0) {
    DateField.value = day + seperator + month + seperator + year;
    }
    /* Error-message if err != 0 */
    else {
    alert("Date is incorrect!");
    //DateField.select();
    //DateField.focus();
    retValue= false;
    }

    return retValue;

    }

    </script>

    <script>
    function ageCount() {
    var field=document.forms["myForm"] ["field"].value
    if (check_date(field)==false){return false};
    var date1 = new Date();
    var dob= document.getElementById("field").value;
    var date2=new Date(dob);
    var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/; //Regex to validate date format (dd/mm/yyyy)
    if (pattern.test(dob)) {
    var y1 = date1.getFullYear(); //getting current year
    var y2 = date2.getFullYear(); //getting dob year
    var age = y1 - y2; //calculating age

    var interest=document.forms ["myForm"] ["interest"].option[0]
    var interest=document.forms ["myForm"] ["interest"].option[1]
    document.getElementById (option[1]); //accesses 2nd option via options

    if (age < 18 && interest==option[1])
    {
    alert('Your age is under 18 and you have ordered an Adult Book. Sorry you are not able to purchase Adult Books. Please choose Childrens Books');
    }



    alert("Age : " + age);
    return true;
    } else {
    alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
    return false;
    }

    }


    </script>
    </head>
    <body>
    <table>
    <form name="myForm" action="mailto:books@books.com.au"" method="post" id="myForm" enctype="multipart/form-data">

    <table width="100%" cellspacing="10" cellpadding="1">
    <TBODY>

    <tr>
    <td colspan="2" align="center"><strong>APPLICATION/ENQUIRY FORM </strong></td></tr>




    <tr>
    <td colspan="2" align="center"><strong>Personal Details:</strong></td>
    </tr>
    <tr>
    <td align="right"><strong>* Last Name</strong></td>
    <td><input name="lastname" type="text" id="lastname" value="Pearce"></td>
    </tr>
    <tr>
    <td align="right"><strong>* First Name</strong></td>
    <td><input name="firstname" type="text" id="firstname" value=Helen></td>
    </tr>
    <tr>
    <td align="right"><strong>* Address</strong></td>
    <td><input name="address" type="text" id="address" value=Wyuna></td>
    </tr>
    <tr>
    <td align="right"><strong>* Suburb</strong></td>
    <td><input name="town" type="text" id="suburb" value = Ballina></td>
    </tr>
    <tr>
    <td align="right"><strong>* State</strong></td>
    <td><select name="state">
    <option value="" selected></option>
    <option value="NSW">NSW</option>
    <option value="QLD">QLD</option>
    <option value="ACT">ACT</option>
    <option value="VIC">VIC</option>
    <option value="WA">WA</option>
    <option value="SA">SA</option>
    <option value="NT">NT</option>
    <option value="TAS">TAS</option>
    </select></td>
    </tr>
    <tr>
    <td align="right"><strong>* Postcode</strong></td>
    <td><input name="postcode" type="text" id="postcode" value =2478 ></td>
    </tr>

    <tr>
    <td align="right"><strong>* Contact Phone</strong ></td>
    <td><input name="cphone" type="text" id="cphone" value = 66815183></td>
    </tr>

    <tr>
    <td align="right"><strong>* Email</strong></td>
    <td><input name="email" type="text" id="email" size="35" maxlength="35" value=hmpk@spin.net.au></td>
    </tr>


    <tr>
    <td align="right"><strong>* Please select your area of interest:</strong></td>

    <td colspan="20" align="left"><select name="interest">
    <option value=""selected></option>
    <option value="1">Books for Children</option>
    <option value="2">Books for Adults</option>

    </select></td></tr>

    <p>
    <tr>
    <td align="right"><strong>* Please enter your date of birth: </strong>


    <td><h6>Insert your date of birth in format dd/mm/yyyy&nbsp;&nbsp; <br>
    <input id="field" type="text" value="" name="field" maxlength="10" size="15"></h6></td>


    </td>
    </tr>
    <tr>
    <td colspan="2" align=center><input name="Button" type="button" onclick="return validateForm()" value="Submit">
    <p> <input onclick="formreset()" value="Reset" type="reset"></p></td>
    </tr>
    </TBODY>
    </table>
    <p></p>
    </form>
    </body>
    </html>

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,080
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    When posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.

    Also, please show only the relevant code.

    var x=document.forms["myForm"]["address"].value
    if (x==null || x==""){

    Form validation of the pattern if (document.formname.formfield.value == "") - that is blank - is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. A proper name may only contain letters, hyphen, space and apostrophe.
    Numeric values, such as zip codes and phone numbers, should be validated as such. Ditto email addresses. This topic has been covered many times before in this forum.

    I think your requirement to be 18 to order adult books is pointless - any 13-year old will have the wit to enter a DOB which is over 18. (Note that the 18 calculation is wrongly based on birth-year only).

    Code:
    var y1 = date1.getFullYear(); //getting current year 
    var y2 = date2.getFullYear(); //getting dob year 
    var age = y1 - y2; //calculating age   NO!
    But your code should be

    Code:
    var int=document.getElementById("myForm").interest.value;  // don't use the same name for an HTML element and a Javascript variable.
    if (age < 18 && int=="2") {
    alert('Your age is under 18 and you have ordered an Adult Book. Sorry you are not able to purchase Adult Books. Please choose Childrens Books');
    }

    Use the search feature of this forum to get a proper check valid date function. And email validator. Your code is 20th century stuff.

    You are trying to use mailto as the form action.
    The trouble with using this long-obsolete method (mailto) to send form results is its unpredictability. The method it is highly dependent on the browser in use
    and the email client in use (some people have only Yahoo, Gmail or Hotmail). In particular, your visitor must have Outlook or Outlook Express or Windows Live Mail as the default client for this to work correctly. Even if your visitor is using Internet Explorer, but the default mail client is different (e.g. Eudora or Thunderbird), your mailto form will not work. With all of the browser troubles, you're likely to lose about half of your users' messages. Most of the email clients that can successfully
    send a mail will prompt the user with a somewhat threatening security dialog prior to sending - this can scare many users from continuing. Other users will not wish to reveal their email address. Also, what about people with Javascript disabled?

    In addition, if you place an unobfuscated email address in your webpage, the bots will quickly find it and inundate you in spam.

    Modern browsers no longer accept mailto: as a form action - they simply open the email program (if any) and ignore the form. If you are going to use a form then use a server-side CGI formmail script as the action - there are several good free ones out there.

    For a simple PHP form feedback script see:- http://www.thesitewizard.com/archive/feedbackphp.shtml
    or http://www.felgall.com/php2.htm


    I don't want to sound discouraging but your code could really do with a substantial re-work. There are many infelicities, example

    x1 = x.replace(/[^a-z]/gi,""); // strip non-alpha chars
    But you never use x1 and in any case a name may contain space hyphen apostrophe (surely not & ?)


    If you are 20 and you are not a socialist, then you have no heart. If you are 40 and you are still a socialist, then you have no brain.
    Last edited by Philip M; 11-09-2012 at 10:47 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,981
    Thanks
    56
    Thanked 557 Times in 554 Posts
    infelicities. Nice word, Philip - I didn't even know it existed

  • Users who have thanked xelawho for this post:

    ElizaKaye (11-11-2012)

  • #4
    New Coder
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Philip

    Thank you very much for your help. I haven't learnt PHP yet. I have only just started out learning HTML and Javascript.

    However when I enter your code in place of my code (see below) it still calculates the age but does not display the message (under 18). Would you kindly let me know what else is missing

    The code I use is the code that has been taught to me through TAFE subjects. I am trying to update my knowledge.
    Code:
    function ageCount() {   
     var field=document.forms["myForm"] ["field"].value
     if (check_date(field)==false){return false};
     var date1 = new Date();       
      var  dob= document.getElementById("field").value;        
      var date2=new Date(dob);        
      var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/; //Regex to validate date format (dd/mm/yyyy)       
       if (pattern.test(dob)) {           
        var y1 = date1.getFullYear(); //getting current year           
    	 var y2 = date2.getFullYear(); //getting dob year            
    	 var age = y1 - y2;           //calculating age  
    	 var int=document.getElementById("myForm").interest.value; 
    		if (age < 18 && int=="2") { 
    		alert('Your age is under 18 and you have ordered an Adult Book. Sorry you are not able to purchase Adult Books. Please choose Childrens Books'); }
    	       
    alert("Age : " + age);
    		   return true;
            } else {
                alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
                return false;
            }
    
       }
    Last edited by ElizaKaye; 11-11-2012 at 07:58 PM. Reason: Sorry I didn't know where to find the cod button before

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,080
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    One more time - When posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.

    Many peope will no bother to even look at code not displayed within the code tags.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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