Developing a simple validation library in JavaScript: continued
(Page 1 of 4 )
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.
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>
<script id="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) {
return false;
}
// 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)) {
return false;
}
// acceptable characters (- . _ 0-9 a-z)
if (oneChar == 45 || oneChar == 46 || oneChar == 95 ||
(oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123))
{
continue;
} else {
return false;
}
}
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))
{
return false;
}
if (oneChar == 45 || oneChar == 46 || oneChar == 95 ||
(oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123))
{
continue;
} else {
return false;
}
}
return true;
}
return false;
}
function Button1_onclick() {
var v = document.all("txtEMail").value;
alert(isValidEmail(v));
}
//-->
</script>
</head>
<body>
<form id="form1">
Enter EMail address:<input type="text" id="txtEMail" NAME="txtEMail"> <input type="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.
Next: Validation for a positive integer (only digits, no symbols) >>
More JavaScript Articles
More By Jagadish Chaterjee