I had need for an email verification script that worked without regex.
I came across a script on the internet and then modified it a little. If you could please test the script out and check that it returns OK as it should that would be great. If there seems to be a problem could you please tell me what the problem is, for example, if a valid email failed the checks (in such a case please tell me what tests it failed) or if there is something important that I have not checked for.
Of course I cannot check for everything that is required from a valid email address, but I’m trying to get the main ideas.
Thanks.
The script below is in HTML format for you to try out.
<html>
<head>
<script language="javascript">
/**
* DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
* Edits, Additions and Reformatting (inc. comments) by Paul Scott (http://www.icio.co.uk/)
*/
function echeck(str) {
// Vars
var at="@";
var dot=".";
var badmail=[];
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
var chars = "@+-._0123456789abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// TEST CHARACTERS
// ******************************
var i;
for (i=0; i<lstr; i++) {
if (chars.indexOf(str.charAt(i))==-1) {
badmail[badmail.length] = 1;
break;
}
}
// OTHER TESTS
// ******************************
// Test for an @, test that @ is not the first character, test @ is not the last character
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
badmail[badmail.length] = 2;
// Test for a ., test that . is not the first character, that . is not the last character
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
badmail[badmail.length] = 3;
// Test that there is only one @
if (str.indexOf(at,(lat+1))!=-1)
badmail[badmail.length] = 4;
// Test that there is not a . before the @, test that there is not a . after the @
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
badmail[badmail.length] = 5;
// Test that there is a . after the @ and that there is a at least 2 characters in between
if (str.indexOf(dot,(lat+3))==-1)
badmail[badmail.length] = 6;
// Test that there are no spaces
if (str.indexOf(" ")!=-1)
badmail[badmail.length] = 7;
// Test that there is a domain extension of >= 2 characters
if (lstr-str.lastIndexOf(dot)<3)
badmail[badmail.length] = 8;
return badmail.length==0?"Email OK":"Email failed the following test:
"+badmail.join(", ");
}
var e = prompt("Enter an email address.
(Cancel to quit).");
while (e != null) {
alert(echeck(e));
e = prompt("Enter an email address.
(Cancel to quit.")
}
</script>
</head>
<body>
</body>
</html>