Blog

Quick Code: Validate Email Address


Here's a simple email validation for PHP: /** * Email validation with MX record check * * @param string $email * * @return bool true or false * * @see http://en.wikipedia.org/wiki/Email_address#Valid_email_addresses * */ function is_valid_email($email) {   if (filter_var($email,FILTER_VALIDATE_EMAIL)) {       getmxrr(substr(strstr($email,'@',false),1),$hosts);       return (bool)$hosts;   }   return false; } Here's my simple regexp version of email validation, which excludes any weird (but valid email addresses), that is:
  • Uppercase and lowercase English letters (a-z, A-Z) (ASCII: 65-90, 97-122)
  • Digits 0 to 9 (ASCII: 48-57)
  • Character . (dot, period, full stop) (ASCII: 46) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively (e.g. John..Doe@example.com is not allowed.).
  /** * Email validation * * @param string $email * * @return bool true or false * * @see http://en.wikipedia.org/wiki/Email_address#Syntax * */ function is_valid_email($email) {   if (         !isset($email{253})         &&         preg_match(               '/                  ^                  (?P[[:alpha:]]+(\.[[:alpha:]]+)*)                  \@                  (?P                     [[:alnum:]]+([\.\-][[:alnum:]]+)*\.[[:alpha:]]{2,4}                     |                     \[\d{1,3}(\.\d{1,3}){3}\]                     |                     [[:xdigit:]]{4}(\:[[:xdigit:]]{4}){7}                  )                  $               /x',               $email,               $email_parts            )      ) {      # local part character limit      if (isset($email_parts['local_part']{64})) {         return false;      }        # domain part limit      if (isset($email_parts['domain']{253})) {         return false;      }        getmxrr($email_parts['domain'],$hosts);      return (bool)$hosts;   }   return false; } You may also want to see: http://php.net/manual/en/function.checkdnsrr.php#109011 http://en.wikipedia.org/wiki/Email_address#Syntax

Comments (0)


Add a Comment





Allowed tags: <b><i><br>Add a new comment:


A Few Accomplishments

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.

Possibly broke spacetime

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Terraformed a small moon

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Snapped dark matter in the wild

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Contact Me

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.