Developing a simple validation library in JavaScript: continued
This series of articles mainly lists some of the most commonly used JavaScript functions for client side validation of HTML forms. You can reuse these scripts to inject into server side controls easily.
Developing a simple validation library in JavaScript: continued (Page 1 of 4 )
All of the examples in this series can be directly tested by simply copying and pasting the entire code (of each section) into any text file with the extension .HTM, then opening it using a browser.
Validation for email addresses – another way
There exist several ways to deal with validation of email addresses. One of the most popular methods is using “regular expressions” (which I already discussed in my previous article). In this section, we shall deal with manual validation of email addresses.
Now, let us try to develop a simple script (JavaScript) to validate email addresses. Have a look at the following code:
<html> <head> <scriptid="clientEventHandlersJS"language="javascript"> <!-- functionisValidEmail(val){ val = val.toLowerCase( ); if (val.indexOf("@") > 1) { var addr = val.substring(0, val.indexOf("@")); var domain = val.substring(val.indexOf("@") + 1, val.length); // at least one top level domain required if (domain.indexOf(".") == -1) { returnfalse; } // parse address portion first, character by character for (var i = 0; i < addr.length; i++) { oneChar = addr.charAt(i).charCodeAt(0); // dot or hyphen not allowed in first position; dot in last if ((i == 0 && (oneChar == 45 || oneChar == 46)) || (i == addr.length - 1 && oneChar == 46)) { returnfalse; } // acceptable characters (- . _ 0-9 a-z) if (oneChar == 45 || oneChar == 46 || oneChar == 95 || (oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123)) { continue; } else { returnfalse; } } for (i = 0; i < domain.length; i++) { oneChar = domain.charAt(i).charCodeAt(0); if ((i == 0 && (oneChar == 45 || oneChar == 46)) || ((i == domain.length - 1 || i == domain.length - 2) && oneChar == 46)) { returnfalse; } if (oneChar == 45 || oneChar == 46 || oneChar == 95 || (oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123)) { continue; } else { returnfalse; } } returntrue; } returnfalse; }
function Button1_onclick() { var v = document.all("txtEMail").value; alert(isValidEmail(v)); } //--> </script> </head> <body> <formid="form1"> Enter EMail address:<inputtype="text"id="txtEMail"NAME="txtEMail"><inputtype="button"value="Validate"id="Button1" name="Button1"onclick="return Button1_onclick()"> </form> </body> </html>
From the above heavy JavaScript, you should now conclude that using “regular expression” (as specified in my previous article) is the best simple method.