Javascript form validation.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manifestcomms
    New Member
    • Mar 2008
    • 2

    Javascript form validation.

    Hello,

    I have a form which requires the fields to be valid before the buttons become active. In particular I am having a problem with the email address field.

    The form is written in PHP using a print function but thats not relevant to my problem. (I am just telling you so it makes it easier to understand why I have used escape chars around the quote marks)

    The e-mail address field is giving me all kinds of problems, in firefox and safari and camino when i enter my email address it gives me the alert saying it is valid but when in IE6 & IE7 it is saying its not valid even though, char for char it is an identical one to that which is valid in FF and is actually a valid address.

    The function testing is triggered on the onkeyup action.

    The email test function is...

    [CODE=javascript]function mailTest(){
    //The string to test.
    var n = document.getEle mentById("formM ail").value.toS tring();
    //How long it is
    var l = n.length;
    //Getting the position of the @ symbol
    var at = n.indexOf("@");
    //Gettng the position of the first dot
    var dot = n.indexOf(".");
    //Array of illegal charachters that should not be in Email addresses
    var badChars = new Array("§","±"," !","¡","€","#", "£","$","%","^" ,"&","*","(",") ","+","="," {","[","}","]",";",":","'"," \"","\\","|","< ",",",">"," ?","/"," ");
    //A variable counting the number of illegal chars, default value is 0
    var badCount = 0;
    //For loop, cycling through the array of illegal characters.
    for(var i=0; i < badChars.length ; i++){
    //If the tested illegal char is in the address string
    if(n.indexOf(ba dChars[i]) != -1){
    //Add 1 to the badChar counter
    badCount++;
    }
    }
    //Get the number of @ symbols in the mail, should only be 1
    var atCount = stringCounter(" @", n);
    //Check the number of . symbols, must be at least 1, have yet to encounter a mail address with more than 4
    var dotCount = stringCounter(" .", n);
    //Check the position of the last . in the address should be after the @ but not immediately, and should be at least 2 chars before the end.
    var lastDot = n.lastIndexOf(" .");
    //Testing if the address is null, or less than 8 chars, where the @ and . symbols are and if it contains any illegal chars
    if(n != "" && l >= 8 && at != -1 && at != 0 && at < l-4 && dot != -1 && dot !=0 && dot != at+1 && dot != at-1 && lastDot >= l-5 && lastDot > at+2 && lastDot < l-2 && badCount == 0 && atCount == 1 && dotCount >= 1 && dotCount <= 4){
    //If all checks pass then it is a valid email address
    mailPass = true;
    alert("email valid");
    }else{
    //If any of the tests fail then the address is not valid.
    mailPass = false;
    alert("email not valid");
    }
    }
    function stringCounter(c harToCount, stringToSearch) {
    //The char we wish to count
    var needle = charToCount;
    //The string we are counting in
    var heystack = stringToSearch;
    //The counter saying how many times the char has occured in the string.
    var counter = 0;
    var myArray = heystack.toLowe rCase();
    for (i=0;i<myArray. length;i++){
    if (myArray[i] == needle){
    counter++;
    }
    }
    return counter;
    }[/CODE]

    I know it is not a perfect syntax checker, yet, but it should work, and does in non IE browsers.

    The HTML which calls the function is...
    [PHP]print("<tr><td> Email Address</td><td><input onkeyup=\"mailT est()\" id=\"formMail\" type=\"text\" name=\"emailAdd \" style=\"width:2 00px;\" />*</td></tr>");[/PHP]

    Any insight is greatly appreciated, kind regards, Michael.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Why don't you use regular expressions?
    All your code could simply be replaced by a single line!
    Code:
    function isValidEmail(value)
    {
    	if (value == null) return false;
    	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    	return filter.test(value);
    }

    Comment

    • lmdbluis
      New Member
      • Mar 2008
      • 1

      #3
      Ok
      First, you should use regular expresions to do this
      Second, you must do the same validation on the server as well bia php if you don't want hackers messing around with your data, also with regular expresions.

      Code:
      //javascript code
      function MailTest(){
      if(document.getElementById("formMail").value.toString().match("^[a-zA-Z0-9]+([\.]?([a-zA-Z0-9_-])+)*@[a-zA-Z0-9]+([\.-]+[a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$")){
      		mailPass = true;
      		alert("email valid");
      	}else{
      		//If any of the tests fail then the address is not valid.
      		mailPass = false;
      		alert("email not valid");
      	}
      }
      Code:
      //php code
      eregi('^[a-z0-9]+([\.]?[a-z0-9_-]+)*@'.'[a-z0-9]+([\.-]+[a-z0-9]+)*\.[a-z]{2,}$',$_POST["Email"])
      //this function tell you if you the email post variable is or not a mail (true|false) you might find a cool way to say, STOP SENDING DATA THROUGH THIS WAY or something (for hackers not to mess up)
      First post here :) and sry if my spelling is not so good but my native language is spanish (from guatemala) :)
      Last edited by gits; Mar 26 '08, 10:25 PM. Reason: removed quote to make post visible

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        just a note ... to shorten the regEx a bit you may write:

        [CODE=javascript]var re = /[a-zA-Z0-9]/;[/CODE]

        for example as:

        [CODE=javascript]var re = /\w/;[/CODE]
        have a look here

        kind regards

        Comment

        • ajeeshdamodar
          New Member
          • Mar 2008
          • 1

          #5
          [CODE=javascript]function Trim(string)
          {
          while (string.substri ng(0,1) == ' ')
          {
          string = string.substrin g(1, string.length);
          }

          while (string.substri ng(string.lengt h-1, string.length) == ' ')
          {
          string = string.substrin g(0,string.leng th-1);
          }
          return string;
          }

          function ValidateEmail(f ield,msg)
          {
          var strValue=field. value ;
          var str =Trim(strValue) ;

          if(str.length!= 0)
          {
          var objRegExp = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
          if(objRegExp.te st(strValue)==t rue)
          {
          return true;
          }
          else
          {
          alert(msg);
          field.focus();
          return false;
          }
          }

          return true;
          }

          function ValidatePhone(f ield,msg)
          {
          /*************** *************** *************** ***
          DESCRIPTION: Validates that a string contains only
          valid integer number.

          PARAMETERS:
          strValue - String to be tested for validity

          RETURNS:
          True if valid, otherwise false.
          *************** *************** *************** *****/
          strValue=field. value;

          var objRegExp = /(^\d\d*$)/;

          //check for integer characters
          var ret= objRegExp.test( strValue);
          if(ret==true)
          {
          return true;
          }
          else
          {
          field.focus();
          alert(msg);
          return false;
          }
          }

          function isValidDate(dat eId)
          {

          var validformat=/^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
          if (!validformat.t est(dateId.valu e))
          {
          alert('Invalid Date.')
          dateId.focus();
          dateId.select() ;
          return false;
          }
          else
          {
          var strDate=dateId. value;
          var dayfield=strDat e.split("/")[1];
          var monthfield=strD ate.split("/")[0];
          var yearfield=strDa te.split("/")[2];
          var dayobj = new Date(monthfield +"/"+dayfield+ "/"+yearfield );
          if (yearfield<1900 ||(dayobj.getMo nth()!=monthfie ld-1)||(dayobj.get Date()!=dayfiel d)||(dayobj.get FullYear()!=yea rfield))
          {
          alert('Invalid Date.')
          dateId.focus();
          dateId.select() ;
          return false;
          }
          return true;
          }
          }

          function IsNotEmpty(fiel d,msg)
          {
          var strTemp = field.value;
          var re = /\s/g; //Match any white space including space, tab, form-feed, etc.
          RegExp.multilin e = true; // IE support
          var str = strTemp.replace (re, "");
          if (str.length == 0)
          {
          field.focus();
          alert(msg);
          return false;
          }

          return true;
          }

          function validateNumeric (field,msg)
          {
          /*************** *************** *************** *************** *****
          DESCRIPTION: Validates that a string contains only valid numbers.

          PARAMETERS:
          strValue - String to be tested for validity

          RETURNS:
          True if valid, otherwise false.
          *************** *************** *************** *************** ******/
          var txtValue=field. value;
          var objRegExp = /(^-?\d\d*\.\d*$)|( ^-?\d\d*$)|(^-?\.\d\d*$)/;

          //check for numeric characters
          var ret= objRegExp.test( txtValue);
          if(ret==true)
          {
          return true;
          }
          else
          {

          field.focus();
          alert(msg);
          return false;
          }
          }

          function ValidateInteger (field)
          {
          /*************** *************** *************** ***
          DESCRIPTION: Validates that a string contains only
          valid integer number.

          PARAMETERS:
          strValue - String to be tested for validity

          RETURNS:
          True if valid, otherwise false.
          *************** *************** *************** *****/
          strValue=field. value;
          var objRegExp = /(^\d\d*$)/;
          // var objRegExp = /(^-\d\d*$)/;

          //check for integer characters
          var ret= objRegExp.test( strValue);
          if(ret==true)
          {
          return true;
          }
          else
          {
          field.focus();
          field.value='';
          alert('Enter an integer value.');
          return false;
          }
          }[/CODE]
          Last edited by gits; Mar 27 '08, 07:23 AM. Reason: added code tags

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5388

            #6
            just a note again ... since you used regEx sometimes you could also shorten the trim function with that:

            [CODE=javascript]function trim(val) {
            return val.replace(/^\s+|\s+$/, '');
            }[/CODE]
            and to shorten the entire code you could consider a function that always does your failure handling like this:

            [CODE=javascript]function handle_failure( node, msg) {
            node.focus();
            alert(msg);
            }
            [/CODE]
            that avoids to repeatedly write the same code ... and just try to write only one exit-point in the functions (only one return statement which is more elegant) ...

            kind regards

            Comment

            • manifestcomms
              New Member
              • Mar 2008
              • 2

              #7
              Originally posted by lmdbluis
              Ok
              First, you should use regular expresions to do this
              Second, you must do the same validation on the server as well bia php if you don't want hackers messing around with your data, also with regular expresions.

              Code:
              //javascript code
              function MailTest(){
              if(document.getElementById("formMail").value.toString().match("^[a-zA-Z0-9]+([\.]?([a-zA-Z0-9_-])+)*@[a-zA-Z0-9]+([\.-]+[a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$")){
              		mailPass = true;
              		alert("email valid");
              	}else{
              		//If any of the tests fail then the address is not valid.
              		mailPass = false;
              		alert("email not valid");
              	}
              }
              Code:
              //php code
              eregi('^[a-z0-9]+([\.]?[a-z0-9_-]+)*@'.'[a-z0-9]+([\.-]+[a-z0-9]+)*\.[a-z]{2,}$',$_POST["Email"])
              //this function tell you if you the email post variable is or not a mail (true|false) you might find a cool way to say, STOP SENDING DATA THROUGH THIS WAY or something (for hackers not to mess up)
              First post here :) and sry if my spelling is not so good but my native language is spanish (from guatemala) :)
              Hello,

              Many thanks for your reply, it was greatly appreciated, and the one I tried first, however on entering the email address once i got to the at symbol and typed in a few more letters it said it was a valid address without entering a dot suffix, e.g. .com or .co.uk. For instance it is saying that mike@yahoo is valid, when it is incomplete.

              Sorry if that doesn't make much sense.

              Thank you to everyone who has posted replies, they have all been very encouraging.

              Im a bit of a regular expressions virgin to be honest so this is something of a nice learning curve.

              Regards.

              Comment

              Working...