469,327 Members | 1,238 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,327 developers. It's quick & easy.

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...

Expand|Select|Wrap|Line Numbers
  1. function mailTest(){
  2.     //The string to test.
  3.     var n = document.getElementById("formMail").value.toString();
  4.     //How long it is
  5.     var l = n.length;
  6.     //Getting the position of the @ symbol
  7.     var at = n.indexOf("@");
  8.     //Gettng the position of the first dot
  9.     var dot = n.indexOf(".");
  10.     //Array of illegal charachters that should not be in Email addresses
  11.     var badChars = new Array("","","!","","","#","","$","%","^","&","*","(",")","+","=","{","[","}","]",";",":","'","\"","\\","|","<",",",">","?","/"," ");
  12.     //A variable counting the number of illegal chars, default value is 0
  13.     var badCount = 0;
  14.     //For loop, cycling through the array of illegal characters.
  15.     for(var i=0; i < badChars.length; i++){
  16.         //If the tested illegal char is in the address string
  17.         if(n.indexOf(badChars[i]) != -1){
  18.             //Add 1 to the badChar counter
  19.             badCount++;
  20.         }
  21.     }
  22.     //Get the number of @ symbols in the mail, should only be 1
  23.     var atCount = stringCounter("@", n);
  24.     //Check the number of . symbols, must be at least 1, have yet to encounter a mail address with more than 4
  25.     var dotCount = stringCounter(".", n);
  26.     //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.
  27.     var lastDot = n.lastIndexOf(".");
  28.     //Testing if the address is null, or less than 8 chars, where the @ and . symbols are and if it contains any illegal chars
  29.     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){
  30.         //If all checks pass then it is a valid email address
  31.         mailPass = true;
  32.         alert("email valid");
  33.     }else{
  34.         //If any of the tests fail then the address is not valid.
  35.         mailPass = false;
  36.         alert("email not valid");
  37.     }
  38. }
  39. function stringCounter(charToCount, stringToSearch){
  40.     //The char we wish to count
  41.     var needle = charToCount;
  42.     //The string we are counting in
  43.     var heystack = stringToSearch;
  44.     //The counter saying how many times the char has occured in the string.
  45.     var counter = 0;
  46.     var myArray = heystack.toLowerCase();
  47.     for (i=0;i<myArray.length;i++){
  48.         if (myArray[i] == needle){
  49.             counter++;
  50.         }
  51.     }
  52.     return counter;
  53. }
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=\"mailTest()\" id=\"formMail\" type=\"text\" name=\"emailAdd\" style=\"width:200px;\" />*</td></tr>");[/PHP]

Any insight is greatly appreciated, kind regards, Michael.
Mar 26 '08 #1
6 1641
chaarmann
785 Expert 512MB
Why don't you use regular expressions?
All your code could simply be replaced by a single line!
Expand|Select|Wrap|Line Numbers
  1. function isValidEmail(value)
  2. {
  3.     if (value == null) return false;
  4.     var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  5.     return filter.test(value);
  6. }
Mar 26 '08 #2
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.

Expand|Select|Wrap|Line Numbers
  1. //javascript code
  2. function MailTest(){
  3. 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,}$")){
  4.         mailPass = true;
  5.         alert("email valid");
  6.     }else{
  7.         //If any of the tests fail then the address is not valid.
  8.         mailPass = false;
  9.         alert("email not valid");
  10.     }
  11. }
Expand|Select|Wrap|Line Numbers
  1. //php code
  2. eregi('^[a-z0-9]+([\.]?[a-z0-9_-]+)*@'.'[a-z0-9]+([\.-]+[a-z0-9]+)*\.[a-z]{2,}$',$_POST["Email"])
  3. //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)
  4.  
  5.  
First post here :) and sry if my spelling is not so good but my native language is spanish (from guatemala) :)
Mar 26 '08 #3
gits
5,390 Expert Mod 4TB
just a note ... to shorten the regEx a bit you may write:

Expand|Select|Wrap|Line Numbers
  1. var re = /[a-zA-Z0-9]/;
for example as:

Expand|Select|Wrap|Line Numbers
  1. var re = /\w/;
have a look here

kind regards
Mar 26 '08 #4
Expand|Select|Wrap|Line Numbers
  1. function Trim(string)
  2.         {
  3.             while (string.substring(0,1) == ' ')
  4.             {
  5.                 string = string.substring(1, string.length);
  6.             }
  7.  
  8.             while (string.substring(string.length-1, string.length) == ' ')
  9.             {
  10.                 string = string.substring(0,string.length-1);
  11.             }
  12.             return string;
  13.         }
  14.  
  15.         function ValidateEmail(field,msg)
  16.         {
  17.             var strValue=field.value ;
  18.             var str =Trim(strValue);
  19.  
  20.             if(str.length!=0)
  21.             {
  22.                 var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
  23.                 if(objRegExp.test(strValue)==true)
  24.                 {
  25.                    return true;
  26.                 }
  27.                 else
  28.                 {
  29.                      alert(msg);
  30.                      field.focus();
  31.                      return false;
  32.                 }
  33.             }
  34.  
  35.             return true;
  36.         }
  37.  
  38.        function ValidatePhone(field,msg)
  39.        {
  40.         /************************************************
  41.         DESCRIPTION: Validates that a string contains only
  42.             valid integer number.
  43.  
  44.         PARAMETERS:
  45.            strValue - String to be tested for validity
  46.  
  47.         RETURNS:
  48.            True if valid, otherwise false.
  49.         **************************************************/
  50.           strValue=field.value;
  51.  
  52.           var objRegExp  = /(^\d\d*$)/;
  53.  
  54.           //check for integer characters
  55.           var ret= objRegExp.test(strValue);
  56.           if(ret==true)
  57.           {
  58.             return true;
  59.           }
  60.           else
  61.           {
  62.             field.focus();
  63.             alert(msg);
  64.             return false;
  65.           }
  66.         }
  67.  
  68.         function isValidDate(dateId)
  69.         {   
  70.  
  71.           var validformat=/^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
  72.           if (!validformat.test(dateId.value))
  73.           {
  74.               alert('Invalid Date.')
  75.               dateId.focus();
  76.               dateId.select();
  77.               return false;
  78.           }
  79.           else
  80.           {     
  81.                var strDate=dateId.value;
  82.                var dayfield=strDate.split("/")[1];
  83.                var monthfield=strDate.split("/")[0];
  84.                var yearfield=strDate.split("/")[2];
  85.                var dayobj = new Date(monthfield+"/"+dayfield+"/"+yearfield);
  86.                if (yearfield<1900||(dayobj.getMonth()!=monthfield-1)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
  87.                {
  88.                      alert('Invalid Date.')
  89.                      dateId.focus();
  90.                      dateId.select();
  91.                      return false;
  92.                }
  93.                return true;
  94.           }
  95.         }
  96.  
  97.         function IsNotEmpty(field,msg)
  98.         {    
  99.             var strTemp = field.value;
  100.             var re = /\s/g; //Match any white space including space, tab, form-feed, etc. 
  101.             RegExp.multiline = true; // IE support
  102.             var str = strTemp.replace(re, "");
  103.             if (str.length == 0)
  104.             {
  105.                 field.focus();
  106.                 alert(msg);
  107.                 return false;
  108.             } 
  109.  
  110.             return true;
  111.         }
  112.  
  113.         function  validateNumeric(field,msg)
  114.         {
  115.             /*****************************************************************
  116.             DESCRIPTION: Validates that a string contains only valid numbers.
  117.  
  118.             PARAMETERS:
  119.                strValue - String to be tested for validity
  120.  
  121.             RETURNS:
  122.                True if valid, otherwise false.
  123.             ******************************************************************/
  124.               var txtValue=field.value;
  125.               var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
  126.  
  127.               //check for numeric characters
  128.               var ret= objRegExp.test(txtValue);
  129.               if(ret==true)
  130.               {
  131.                 return true;
  132.               }
  133.               else
  134.               {
  135.  
  136.                 field.focus();
  137.                 alert(msg);
  138.                 return false;
  139.               }
  140.        }
  141.  
  142.        function ValidateInteger(field)
  143.        {
  144.         /************************************************
  145.         DESCRIPTION: Validates that a string contains only
  146.             valid integer number.
  147.  
  148.         PARAMETERS:
  149.            strValue - String to be tested for validity
  150.  
  151.         RETURNS:
  152.            True if valid, otherwise false.
  153.         **************************************************/
  154.           strValue=field.value;
  155.           var objRegExp  = /(^\d\d*$)/;
  156.          // var objRegExp  = /(^-\d\d*$)/;
  157.  
  158.           //check for integer characters
  159.           var ret= objRegExp.test(strValue);
  160.           if(ret==true)
  161.           {
  162.             return true;
  163.           }
  164.           else
  165.           {
  166.             field.focus();
  167.             field.value='';
  168.             alert('Enter an integer value.');
  169.             return false;
  170.           }
  171.         }
Mar 27 '08 #5
gits
5,390 Expert Mod 4TB
just a note again ... since you used regEx sometimes you could also shorten the trim function with that:

Expand|Select|Wrap|Line Numbers
  1. function trim(val) {
  2.     return val.replace(/^\s+|\s+$/, '');
  3. }
and to shorten the entire code you could consider a function that always does your failure handling like this:

Expand|Select|Wrap|Line Numbers
  1. function handle_failure(node, msg) {
  2.     node.focus();
  3.     alert(msg);
  4. }
  5.  
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
Mar 27 '08 #6
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.

Expand|Select|Wrap|Line Numbers
  1. //javascript code
  2. function MailTest(){
  3. 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,}$")){
  4.         mailPass = true;
  5.         alert("email valid");
  6.     }else{
  7.         //If any of the tests fail then the address is not valid.
  8.         mailPass = false;
  9.         alert("email not valid");
  10.     }
  11. }
Expand|Select|Wrap|Line Numbers
  1. //php code
  2. eregi('^[a-z0-9]+([\.]?[a-z0-9_-]+)*@'.'[a-z0-9]+([\.-]+[a-z0-9]+)*\.[a-z]{2,}$',$_POST["Email"])
  3. //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)
  4.  
  5.  
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.
Mar 27 '08 #7

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Madha K | last post: by
7 posts views Thread by mhk | last post: by
5 posts views Thread by | last post: by
2 posts views Thread by daniel.boorn | last post: by
27 posts views Thread by Chris | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by listenups61195 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.