Miltery Proof Strong Javascript EMail Validation  

Posted by Hanush H Nair in ,

After several hours of stunt with my tester, I think I made something very much useful. Email validation is very much common requirement for almost all project. However, the codes which are available for the same on the internet seems in-effective.

You are free to use this on your open source as-well-as commercial projects.



/*
* E-mail Validation
* @param value
*/
function validateEmail(elementValue){
var ind=elementValue.indexOf("@");
var email_local_part=elementValue.slice(0,ind);

if(email_local_part.length > 64) return false;
if(elementValue > 256) return false;
var x,y=email_local_part;

if(email_local_part.charAt(((email_local_part.length)-1)) == ".") return false;

while(y.indexOf(".")!=-1){
x = y.indexOf(".");
if(y.charAt(x+1) == ".") return false;
x++;
y=y.substr(x);
}
var dot = ".";
if( isInteger( elementValue.charAt(0) )) return false;
if( elementValue.charAt(0) == dot ) return false;

var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);

}

/*
* Trim implementation for Javascript
*/
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/*
* Checks whether the input is an Integer
*/
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
return true;
}




Implementation

if(!validateEmail("abc@gmail.com")){
alert("Invalid Email");
}