473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript form validation.

2 New Member
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=\"mailT est()\" id=\"formMail\" type=\"text\" name=\"emailAdd \" style=\"width:2 00px;\" />*</td></tr>");[/PHP]

Any insight is greatly appreciated, kind regards, Michael.
Mar 26 '08 #1
6 1785
chaarmann
785 Recognized Expert Contributor
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
lmdbluis
1 New Member
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 Recognized Expert Moderator Expert
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
ajeeshdamodar
1 New Member
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 Recognized Expert Moderator Expert
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
manifestcomms
2 New Member
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
2675
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 function to verify the name fields, age, email and gender. My question is: if I create a function for each field like the code below, what would be the best way to organize the functions and call them? Would I need one main function and place...
2
1444
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 representation can be saved as a string and recreated. (The application also has a crude workflow aspect - so XMHTML forms can be created and assigned a workflow. Forget I said anything about
4
9464
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 non-utf8 characters? 2) Using javascript how to find the lengh of a string having unicode characters? e.g: For a field Name on the form, there is a corrosponding field Name varchar2(10) in DB. Through my application when i try enter 10 normal...
7
14280
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
2131
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 roundtrip to the server. The codebehind seems to be unaware of select box members populated via javascript. So, I'm having to create my own state management solution, (i.e. rewriting the VIEWSTATE mechanism) to persist the state of these select...
1
3252
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 other input fields available to fill in. I use the JavaScript OnChange function (=clientside) that creates a querystring and does a refresh of the page. It works fine.
5
2637
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 in 1.1 since I could edit the .js file. Now in 2.0 I can no longer do this. Also, my code would have to be called after all client-side validation was done and was successful. Any ideas? TIA!
2
2359
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! For example: A normal HTML form with out validation: <form action="foobar.htm" method="get"> <div>Name: <input type="text" name="customerName" value=""></div>
27
4728
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 appears that the data goes straight to the processing page, rather than the javascript seeing if data is missing and popping up an alert. I thought it may be because much of the form is populated with data from the db (lists, etc.), but when I leave...
5
19069
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 zip file referenced on http://www.javascript-coder.com/html-form/javascript-form-validation.phtml I managed to get everything working and was testing through Firefox that alerts were generated. However at the very end I thought I'd better check...
0
8326
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8743
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.