Community Documentation

Email address validation with domain name

Last updated March 13, 2012. Created by anbuindia on March 29, 2010.
Edited by danjuls, silverwing. Log in to edit this page.

Use the following function to validate the email address with valid domain.It returns TRUE on success and FALSE on failure.

Eg:
anbu_rajendran@yahoo.co.in is a valid email.

abc@abc.com is not a valid email.

/**************************************/

function email_validate($email) {
  $isValid = true;
  $atIndex = strrpos($email, "@");
  if(is_bool($atIndex) && !$atIndex) {
    $isValid = false;
  }
  else {
   $domain = substr($email, $atIndex+1);
   $local = substr($email, 0, $atIndex);
   $localLen = strlen($local);
   $domainLen = strlen($domain);
   if($localLen < 1 || $localLen > 64) {
      // local part length exceeded
      $isValid = false;
   } else if($domainLen < 1 || $domainLen > 255) {
     // domain part length exceeded
     $isValid = false;
   } else if($local[0] == '.' || $local[$localLen-1] == '.') {
     // local part starts or ends with '.'
     $isValid = false;
   } else if(preg_match('/\\.\\./', $local)) {
      // local part has two consecutive dots
      $isValid = false;
   } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
       // character not valid in domain part
       $isValid = false;
   } else if(preg_match('/\\.\\./', $domain)) {
       // domain part has two consecutive dots
       $isValid = false;
   } else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
       // character not valid in local part unless
       // local part is quoted
       if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
         $isValid = false;
       }
   }
   if($isValid && !(checkdnsrr($domain,"MX") ||  checkdnsrr($domain,"A"))) {
      // domain not found in DNS
      $isValid = false;
    }
   }
   return $isValid;
}

/********************************/

About this page

Drupal version
Drupal 5.x, Drupal 6.x
Audience
Programmers
Keywords
domain, validate email

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.