JavaScript To Check Valid Email Address

This is an article on JavaScript To Check Valid Email Address in JavaScript and AJAX.

While designing web pages we several time needs scripts that check our data and validate it. Checking Email address file is one of the most commonly used scripts which we need for all registration purpose.

While checking email, we need to focus on following points.

An email address contain '@' symbol.

An email address contain '@' symbol.

An email address also contain a '.' (dot) symbol. After finding the @ symbol we must encounter a '.' (dot) symbol in host name. It used in defining host name like gmail.com, yahoo.com.

An email address must have a length of minimum 5 characters. That is, username@hostname or we can say that the smallest email address can be 'a@a.c'. You can change the minimum number to 6 characters as we assume that in smallest email address the hostname is 'a.c' but in real the domain name contain at least two characters ( like .in , .tk , .us etc. ).

Thus we need these 3 condition checked before sending the information to the server.

<SCRIPT language=JavaScript ><!-- function Validator(theForm){// If email field is null it will show an error.if( theForm.email_id.value == ""){alert("Please enter a Email ID for the field."); theForm.email_id.focus();return(false);}

var check_at = "@"; // '@' character to be checked in Email ID. Either its present or not. If its present we will check other condition. Else it a invalid ID.

var check_dot = "."// to check '.' (dot)character in the host name. var checkStr = theForm.email_id.value;var allValid = false; // this is use to check whether all condition is true or not. If all condition evaluate true then this will turns to true and our form will be forwarded to next page.

for(i = 0; i < checkStr.length; i++){ ch_at = checkStr.charAt(i);

// Here checking for all in valid character. I am checking '~' , '`' , '!' , '#' character as invalid character for an Email ID field. If we found any if this character in my email id, we just need to truncate the loop any making allValids = false. if(ch_at == '~' || ch_at == '`' || ch_at == '!' || ch_at == '#'){ allValid = false;break;}

if(ch_at == check_at)// checking for '@' character in ID.{for(j = i+2; j < checkStr.length; j++)// if found '@' character then the we must check for '.' (dot) character. It will be at more than +2 position after finding the '@' character. { ch_dot = checkStr.charAt(j);

if(ch_dot == check_dot && checkStr.charAt(j+1) != "")// after finding '.' (dot) character there must be one character so it is checked by checkStr.charAt(j+1) function.{ allValid = true;break;}}}}

if(!allValid)// if allValid fails then it will show a alert message.{alert("Please enter a valid Email ID for field."); theForm.email_id.focus();return(false);}else// if allvalid is not false then it will forward the information to next page.{return(true);}