473,394 Members | 1,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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

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

Similar topics

5
by: Sue | last post by:
After finishing up my first quarter JavaScript on 12/12/03, I decided to improve character checking on my project. In my project I only had to do very basic validation. Therefore, I only had one...
2
by: GIMME | last post by:
Background ... I've created a web application that allows a user to create an HTML application from IE. The application itself creates an XML representation of a XHTML form. The XHTML...
4
by: Madha K | last post by:
I am developing a web application that need to support UTF-8 characters. For client side validations, can javascript be used to handle UTF-8 characters. 1) How javascript can be used to restrict...
7
by: mhk | last post by:
Hi, Is there any way to create/set Session veriable in JavaScript. Please let me know if anyone has an idea. Thanks alot.
5
by: Allan M. | last post by:
I have a series of select boxes that must be populated client side, because they interact with each other. The design specification calls for these boxes to be updated without having to make a...
1
by: IkBenHet | last post by:
Hello, Currently I am using a large input form on a website that is based on ASP and JavaScript. Depending on the values that are filled in by the user the forms does a refresh and makes...
5
by: | last post by:
Hi all, Has anyone been able to write some custom javascript on the onclick event of submit button to do certain things like disable submit button, only submit form once etc. This was a breeze...
2
by: daniel.boorn | last post by:
Form validation using JavaScript has never been as easy and simple! We have developed a free generic form validation script that can validate any form with very little JavaScript required in form!...
27
by: Chris | last post by:
Hi, I have a form for uploading documents and inserting the data into a mysql db. I would like to validate the form. I have tried a couple of Javascript form validation functions, but it...
5
by: cbs7 | last post by:
Hi all I'm a complete newbie to web development and Javascript especially. I've been creating a form for a webpage and have used a validation script gen_validatorv2.js which I downloaded from the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.