Validate an email addressTag(s): Language


It's impossible to check if an address is REALLY valid but we can check for the presence of the "@" character.
<HTML><HEAD>
<SCRIPT>

function validate_email() {
    if(-1 == document.jsform.email.value.indexOf("@")) {
       document.jsform.email.focus();
       alert("Your email must have a '@'.");
       return false;
       }
    if(-1 != document.jsform.email.value.indexOf(",")) {
       document.jsform.email.focus();
       alert("Your email must not have a ',' in it");
       return false;
       }
    if(-1 != document.jsform.email.value.indexOf("#")) {
       document.jsform.email.focus();
       alert("Your email must not have an '#' in it." );
       return false;
       }
    if(-1 != document.jsform.email.value.indexOf("!")) {
       document.jsform.email.focus();
       alert("Your email must not have a '!' in it." );
       return false;
       }
    if(-1 != document.jsform.email.value.indexOf(" ")) {
       document.jsform.email.focus();
       alert("Your email must not have a space in it." );
       return false;
       }
    if(document.jsform.email.value.length ==
         (document.jsform.email.value.indexOf("@")+1) ) {
       document.jsform.email.focus();
       alert("Your email must have a domain name after the '@'.");
       return false;
       }

    if(document.jsform.email.value.length == 0) {
      document.jsform.email.focus();
      alert("Please enter your email.");
      return false;
      }

    return true;
  }
</SCRIPT><BODY>
Press ENTER to validate this email address
<FORM NAME="jsform"
      ONSUBMIT="return validate_email()">
<INPUT NAME="email"
       TYPE="text"
       SIZE="50">
</FORM></BODY></HTML>

Alternate way using regular expression:

<script>
function checkemail(str){
   var filter=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/

   if ( !filter.test(str)) {
    alert ("bad");
    return false;
   }
   else {
    alert ("ok");
    return true;
  }
}
</script>


Press ENTER to validate this email address
<FORM NAME="jsform"
      ONSUBMIT="return checkemail(document.jsform.email.value)">
<INPUT NAME="email"
       TYPE="text"
       SIZE="50">
</FORM>


While you can't validate that an email address is a real one, you can check if the domain name is real. You will find a tool to do that at this site.
blog comments powered by Disqus