Sullivan Market

a web based full-circle development system



My JavaScript Tutorials - Email Validation

Here's the Javascript that does the actual validation of the email address. Save this to a separate file and call it emailcheck.js:

function submitTo(pPage) {
document.forms[0].action = pPage;
document.forms[0].submit(this.form);
}

function setValues() {

}

function check()
{
var missing = 0;
var msg = "Please correct the following error(s):\n\n";
var p3 = document.forms[0].pEmail1.value;
var p4 = document.forms[0].pEmail2.value;

//Variables for validating Email addresses for proper format
var str1 = document.forms[0].pEmail1.value;
var str2 = document.forms[0].pEmail1.value;
var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
var skip = false;
if (str1.length > 0){
if (!reg1.test(str1) && reg2.test(str1)) { // if syntax is valid
skip = true;
}
if (skip == false){
missing++;
msg = msg + " - Your Old Email, " + str1 + ", is invalid." + "\n";
}
}
if (str2.length > 0){
if (!reg1.test(str2) && reg2.test(str2)) { // if syntax is valid
skip = true;
}
if (skip == false){
missing++;
msg = msg + " - Your New Email, " + str2 + ", is invalid." + "\n";
}
}

if (missing > 0){
alert(msg);
return false;
}
else
return true;
}

Here's the code for the actual webpage:

<HTML>
<HEAD>
<TITLE>Email Validation</TITLE>

<SCRIPT language=JavaScript src="emailcheck.js"></SCRIPT>
</HEAD>
<BODY>
<form name="frm" onsubmit="return check()" action="#" method="post">
<table><tbody>
<tr>
<td vAlign="top" height="25">E-Mail:</td>
<td vAlign="top" height="25"><input name="pEmail1" maxLenght="12"></td>
</tr>

</tbody></table>
<input type="Submit" name="cmdSearch" value="Search">
<input type="Reset" name="cmdReset" value="Reset">
</form>

</BODY>
</HTML>

Note:: Make sure that, for this example, you place all the files within the same folder.

Back To JavaScript Tutorials

©2012 SullivanMarket.com