Got RegEx?
There's a right way and a wrong way and another way
I found this email address validation algorithm lurking in some code that I was tweaking:
i =document.mailform.femail.value.indexOf("@")
j =document.mailform.femail.value.indexOf(".",i)
k =document.mailform.femail.value.indexOf(",")
kk =document.mailform.femail.value.indexOf(" ")
jj =document.mailform.femail.value.lastIndexOf(".")+1
len =document.mailform.femail.value.length
if((i>0) && (j > (i+1)) && (k==-1) && (len -jj >=2) && (len-jj<=3))
{
return true;
}
else
{
alert("Please use correct E-mail format in the \"Your Friend\'s Email\" field.\n" +
document.mailform.femail.value + " is invalid.");
return false;
}
The above code works fine. kinda-sorta, but its a little ugly. I like 'regular expressions', so this is how I would do the same thing:
var emailRegEx = [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|
biz|info|mobi|name|aero|jobs|museum)\b;
if (document.mailform.femail.value.match(emailRegEx))
{
return true;
}
else
{
alert("Please use correct E-mail format in the \"Your Friend\'s Email\" field.\n" +
document.mailform.femail.value + " is invalid.");
return false;
}
Now, looking at my code snippet, its pretty clear whats happening: the email address is being validated again 'emailRegEx', which will return 'true' if it matchs or 'false' if it doesn't. Plus, it catches on when someone is trying to enter an email address like fkljhfsd@klhfsd.sfk, which the first code segment would be perfectly happy with.
Of course, the regular expression can be called 'ugly', too, but I think its quite elegant.. beautiful, even. And I didn't have to make it up, either (every regular expression you could ever need can be found here or on any one of 100 other similar sites).
Keep it simple, keep it clean, and don't re-invent the wheel. I dunno.. its just the way I was raised... :O)