Quick Email Address Validation Script

You should never have a website or script that takes in an e-mail address without at least doing some basic low-level validation.  At a minimum verifying that the positions of the “.” and “@” characters are in the right spot and so forth.

Below is a quick and dirty one that I have used before in some personal sites.  There are many opinions out there on the web about how strict to check for valid e-mail addresses.  My opinion is to check the basic high level structure but to avoid checking the nitty-gritty details and being too strict.  Generally speaking I would rather put as few blockers as possible into my e-mail collection scripts so that it is as easy as possible for a user to enter their e-mail.  I can then later run automated trials or confirmation messages against the e-mail address to test its validity.

function checkEmail($email){
  $minLength = 2;
  $dot = strrpos($email, '.');
  $at = strrpos($email, '@');
  $length = strlen($email);
  $validEmail = true;

  //Validate the various items above all exist
  if($dot === false || $at === false || $length === false){
    $validEmail = false;
  }

  //Validate minimum length requirements
  if(($dot - $at) <= $minLength || ($length - $dot) <= $minLength){
    $validEmail = false;
  }

  return $validEmail;
}

Comments

comments

Posted in and tagged , .