Using regexp to validate simple form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TokyoJ
    New Member
    • Dec 2006
    • 8

    Using regexp to validate simple form

    I run a small camp in Alaska for kids and my director is asking for a web form. Could someone please have a look and offer some advice on where I'm making mistake(s)?
    I'm using the RegExp function to validate 3 types of fields: text, radio button, dropdown menu. but the code doesn't validate. After 2 days, it's time I asked for guidence.
    Criteria:
    Text: only alphabet, no numerals, allowed
    Radio: one must be selected,
    Dropdown: an option must be selected.
    Phone number: exactly 10 digits.
    Email: can only come from domains: .com, .net, .gov, OR .edu (haven't yet asked 'why?' but that's what the director's asking for)

    Goal:
    1. I don't want all the errors to come up inside one alert, but rather have one alert show at a time. After one entry error is corrected, the next error will appear after clicking submit again. For example, if the form is sent blank, ONLY the Alert, "Please enter your name." appears because it is the first field.

    2. Once the form is completed correctly, an alert saying, "Thank you for completing the form." pops up in front of the new page which the SUBMIT button leads to.

    I'm an advanced/beginner catching up on JS. The VAR for GENDER and CITY have been left empty on purpose, simply because I don't know how to enter the correct info.
    There are other text fields and radio buttons in the full version of form so if I can get these validations to work, I'll be good to go with the others.
    Thank you in advance for your insight.
    Both the JS and HTML are given below.
    TokyoJ

    [HTML]<HTML> <HEAD><TITLE> Form </TITLE>
    <script language="javas cript">
    <!--
    function validate (){
    var fullname = document.module 102form.fullnam e.value;
    var gender = document.module 102form.gender. value;
    var country = document.module 102form.city.va lue;
    var email = document.module 102form.email.v alue;

    var fullnameRegExp=/\d/;
    var genderRegExp=/ /;
    var countryRegExp=/ /;
    var emailRegExp=/^[@]||[.com]||[.net]||[.edu]||[.gov] /\g;

    if (fullnameRegExp .test(fullname) !=true)
    alert("Please reenter your FULL NAME.");
    if (genderRegExp.t est(gender)= unchecked)
    alert("Please select a GENDER.");
    if (countryRegExp. test(country)!= true)
    alert("Please select a CITY.");
    if (emailRegExp.te st(email)!=true )
    alert("Please valid EMAIL.");
    else {

    alert("Thanks for completing the form.");
    document.module 102.action.valu e="http://nova.crs.com/cgi-bin/cgiwrap/~em680a04/module102.php";
    }
    }
    //-->
    </script>
    </HEAD>
    <BODY>
    <FORM METHOD="post" name="module102 form" onSubmit="retur n validate(this); " ACTION="http://nova.crs.com/cgi-bin/cgiwrap/~em680a04/module102.php">
    <!-- START HTML -->
    <TABLE>
    <TR>
    <TD> FULL NAME: </TD>
    <TD><INPUT NAME="fullname" TYPE="text"> </TD>
    </TR>
    <TR>
    <TD> GENDER: </TD>
    <TD><INPUT TYPE="radio" NAME="gender" VALUE="Male"> MALE <INPUT TYPE="radio" NAME="gender" VALUE="Female" > FEMALE </TD>
    </TR>
    <TR>
    <TD>COUNTRY:</TD>
    <TD><SELECT NAME="country">
    <OPTION VALUE="select"> Please select a city</option>
    <OPTION VALUE="anchorag e"> Anchorage </option>
    <OPTION VALUE="fairbank s"> Fairbanks</option>
    <OPTION VALUE="juneau"> Juneau </option>
    </SELECT></TD>
    </TR>
    <TR>
    <TD> EMAIL: </TD>
    <TD><INPUT NAME="email" TYPE="text"> </TD>
    </TR>
    </TABLE>
    <!-- BUTTON -->
    <tr>
    <td> <INPUT TYPE="submit" VALUE="SEND DATA"><INPUT TYPE="reset" VALUE="CLEAR FORM"> </td>
    </tr>
    </FORM>
    </BODY>
    </HTML>[/HTML]
    Last edited by TokyoJ; Dec 4 '06, 09:35 AM. Reason: spelling error.
  • Hagelbrakare
    New Member
    • Dec 2006
    • 23

    #2
    Hi! I made a few changes in you javascript code. I'm not sure what you wanted to check when it comes to fullname, but you checked if it did not contain a digit which I'm quite sure you didn't meen to :) Now it checks if it is a full name ( ex "chandler bing" or "chandler bing bong") not just "chandler".

    Gender will actually return an array because there are two elements with same name. You have to check if either of them are checked.

    contry.value will return "select" when no city is selected. I suppose that it should be city all the way.

    validating an e-mail is hard, but this little regex just checks the end.

    Code:
    function validate () {
    	var fullname = document.module102form.fullname.value;
    	var country = document.module102form.country.value;
    	var email = document.module102form.email.value;
    		
    	var fullnameRegExp=/^\D+( \D+)+$/;
    	var emailRegExp=/[.](com|net|edu|gov)$/;
    		
    	if (!fullnameRegExp.test(fullname)) {
    	    alert("Please reenter your FULL NAME.");
    	    return false;
    	}
    		
    	if (!document.module102form.gender[0].checked && !document.module102form.gender[1].checked) {
    	    alert("Please select a GENDER.");
    	    return false;
    	}
    
    	if (country == "select") {
    	    alert("Please select a CITY.");
    	    return false;
    	}
    
    	if (!emailRegExp.test(email)) {
    	    alert("Please valid EMAIL."); 
    	    return false;
    	}
    
    	alert("Thanks for completing the form.");
    	return true;
    }

    Comment

    • TokyoJ
      New Member
      • Dec 2006
      • 8

      #3
      Hagelbrakare,
      Thank you. I'm dusting off my brain so the changes you made are clear.

      So is this the correct onSubmit?
      onSubmit="retur n validate(this); "

      I'm not clear on the differences between
      onSubmit="retur n validate(this); "
      and
      onSubmit="retur n validate_form() ;"
      and
      onSubmit="retur n validate();"

      Could you explain which is best for this form(in simple terms)?
      Cheers,
      John

      Comment

      • Hagelbrakare
        New Member
        • Dec 2006
        • 23

        #4
        I'm sorry, I forgot to tell you.

        As you can see the function is declared as "function validate()" which meens that functions name is validate and that it takes no arguments (the parentesis is empty). This meens that you should call it by validate(). validate() will return true or false. onsubmit should return what validate returns. I know that is sounds a little bit too much already, but onsubmit="retur n validate()" will to the job.

        You are welcome to ask as many questions as you want :) Is there anything in the javascript function that puzzles you?

        Comment

        • TokyoJ
          New Member
          • Dec 2006
          • 8

          #5
          That clears it up and makes sense. Used onSubmit return validate (); and worked well.
          One point I'm still vague on is this... for validations, when using

          Code:
          var fullname = document.feedback.fullname.value;// TEXT BOX
          var city = document.feedback.city.value;          // DROPDOWN 
          var gender = document.feedback.gender.value;  	// DROPDOWN
          var area = document.feedback.area.value; 	// TEXT BOX
          		
          var fullnameRegExp=/^\D+( \D+)+$/;
          var emailRegExp=/[.](com|net|edu|gov)$/;
          var areaRegExp=/^[a-zA-z]+$ /;
          var cityRegExp=/ /;
          var phoneRegExp=/ /;
          var cellRegExp=/ /;
          var emailRegExp=/ /;.

          Comment

          • TokyoJ
            New Member
            • Dec 2006
            • 8

            #6
            (my 5 min of allowed 'edit' time expired so am posting a new reply)
            Thank you. That makes sense and it works.
            There is one point that I'm getting hung up on...using VAR in RegExp validations. For example here I use 4 fields, fullname, gender, city, and interests; each with a different input style.

            var fullname = document.feedba ck.fullname.val ue; // TEXT BOX
            var city= document.feedba ck.city.value; // DROPDOWN MENU
            var interest = document.feedba ck.interest.val ue; // CHECKBOX
            var gender = document.feedba ck.gender.value ; // RADIO BUTTON

            then in the next step, xxxRegExp is used for only TEXTBOX var's, such as
            var fullnameRegExp=/^\D+( \D+)+$/;
            correct?

            If so then this leaves RADIO BUTTONS, DROPDOWN MENUS and CHECKBOXES to be validated later in the code, in a type of 'self-contained' (if that makes sense) expression. Such as

            if (city == "select") {
            alert("Please select a CITY.");
            return false;
            }


            Am I thinking on the right track in why xxxRegExp is used for only some of the VAR's and not others?
            Thank you.

            Comment

            • Hagelbrakare
              New Member
              • Dec 2006
              • 23

              #7
              Using regular expression to validate a select box is some what overkill.

              Code:
              <select name="s_city">
              <option value="">- Choose a city -</option>
              <option value="New York">New York</option>
              </select>
              In this case the value of the select will be an empty string if the user didn't selected a city. You can decide what value it will get. You don't need a regular expression because the user simply can not choose something else.

              When it comes to the area code you can use a regex. I don't know how such a code looks because I'm not american, but the example you gave would except everything from "a" to "aaaaafffffffff sssssssssdddddd dddd".

              Comment

              • Hagelbrakare
                New Member
                • Dec 2006
                • 23

                #8
                Checkboxex and radio buttons are a different story. They are checked.

                If you have a checkbox you just check if it's checked.

                Code:
                if (document.myform.mycb.checked)
                do something;
                With radio buttons you get the an array with all radio button with the same name. Unless it's just one, then it will work just like a checkbox.

                Code:
                <input type="radio" name="car">BMW
                <input type="radio" name="car">Mercedes
                <input type="radio" name="car">Jaguar
                
                if (document.myform.car[0].checked) // you have a bmw
                if (document.myform.car[1].checked) // you have a mercedes
                if (document.myform.car[2].checked) // you have a jaguar.

                Comment

                • TokyoJ
                  New Member
                  • Dec 2006
                  • 8

                  #9
                  That makes sense. Thank you. I'll make a note of the radio button examples.
                  BTW I'm not american either. I just happen to live in Alaska for work...hopefull y I'll be able to find a job in a warmer climate. :-)
                  Thank you for your help.
                  It is greatly appreciated.

                  Comment

                  • Hagelbrakare
                    New Member
                    • Dec 2006
                    • 23

                    #10
                    You're welcome :) Warmer climate could work for me too :) I live in Sweden. Probably not as cold as Alaska, but not like Thailand either ;)

                    Comment

                    • TokyoJ
                      New Member
                      • Dec 2006
                      • 8

                      #11
                      Tack själv.
                      Everying I've seen/read/heard about Sweden has been good. Very few countries can say that.
                      Can I ask one more question?
                      Using the two below VAR's, as examples, what script could I use to make sure the phone # and cell # are different? Alert appears if user enters the same # in both fields. (it's not a big issue, just want to learn more).

                      Thank you for taking the time to educate a lesser skilled person.
                      var phone = document.feedba ck.phone.value;
                      var cell = document.feedba ck.cell.value;

                      and
                      if (!phoneRegExp.t est(phone)) {
                      alert("Please reenter your PHONE NUMBER.");
                      return false;
                      }
                      if (!cellRegExp.te st(cell)) {
                      alert("Please reenter your CELL NUMBER.");
                      return false;
                      }

                      Cheers,

                      Comment

                      • Hagelbrakare
                        New Member
                        • Dec 2006
                        • 23

                        #12
                        I'm glad that you think that Sweden might be a good place to be :)

                        This little snippet of code will validate the number and check if they're identical. I was assuming that a phone # can start with "+".

                        Code:
                        function checkPhones() {
                        	var reNumber = /^[+]?\d+$/;
                        	var vPhone = document.getElementById("t_phone").value;
                        	var vCell = document.getElementById("t_cell").value;
                        	
                        	if (!reNumber.test(vPhone)) {
                        		alert("Not valid Phone Number");
                        		return;
                        	}
                        	if (!reNumber.test(vCell)) {
                        		alert("Not valid Cell Phone Number");
                        		return;
                        	}
                        	if (vPhone == vCell) {
                        		alert("The numbers are identical");
                        		return;
                        	}
                        	
                        	alert("They're good");
                        }

                        Comment

                        Working...