Email validation - regular expression

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikeman
Forum Newbie
Posts: 18
Joined: Wed Apr 07, 2010 7:18 am

Email validation - regular expression

Post by mikeman »

I wrote this reg exp and thought that it would reject a someone@domain.co.uk as I had not put a full stop in the final statement - but it is validating even with the dot between the co and uk! Any ideas why?

Code: Select all

if(preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,6})$/', $textbox)) {
				echo "Valid!";
			} else {
				echo "Invalid!";
			}
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Email validation - regular expression

Post by Apollo »

You are allowing dots in the first [ ] part after the @ character.
Therefore domain.co matches [a-zA-Z0-9._-]+ and then uk matches the last [a-zA-Z]{2,6} part.

Furthermore it's really not wise (nor necessary) to reinvent a wheel that has obviously been invented many times before.

For example, take the RFC 2822 complient regexp from www.regular-expressions.info:

Code: Select all

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Email validation - regular expression

Post by AbraCadaver »

Or:

Code: Select all

filter_var($email, FILTER_VALIDATE_EMAIL);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
buckit
Forum Contributor
Posts: 169
Joined: Fri Jan 01, 2010 10:21 am

Re: Email validation - regular expression

Post by buckit »

Here is the function I use to validate email addresses. it checks to make sure its a valid format and checks that the domain (ie gmail.com) is actually a valid domain by checking MX records.

I havent ever had any issues with it... I didnt write it and for the life of me I can't figure out where the hell I got it from. if you see this and you wrote it! all credit due!

Code: Select all


function validEmail($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;
}

User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Email validation - regular expression

Post by AbraCadaver »

I didn't look through all the code, but I definitely wouldn't take credit for that if this is all that is needed: 8)

Code: Select all

function validEmail($email) {
	if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
		list($name, $domain) = explode('@', $email);
		if(getmxrr($domain)) {
			return true;
		}
	}
	return false;
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: Email validation - regular expression

Post by Bind »

AbraCadaver,

I did look through the code.

Filters were not present in php prior to version 5.2, so the script posted (that you are blasting and dismissing without even reading it) was a valid way to do it.

Additionally, there are many hosting enviroments still not updated to the current php version that filters can not be used on.

I do not think any of us here want to read your thinly vieled slights on code posted by others, who are only trying to assist others. I know I am not.

This is a resource for learning and helping others - not a place to flame others who are actively helping people.



Buckit,

Thank you for posting your code, as I am sure it will help many people who are using an older version of PHP that can't use filters.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Email validation - regular expression

Post by AbraCadaver »

Bind wrote:AbraCadaver,

I did look through the code.

Filters were not present in php prior to version 5.2, so the script posted (that you are blasting and dismissing without even reading it) was a valid way to do it.

Additionally, there are many hosting enviroments still not updated to the current php version that filters can not be used on.

I do not think any of us here want to read your thinly vieled slights on code posted by others, who are only trying to assist others. I know I am not.

This is a resource for learning and helping others - not a place to flame others who are actively helping people.



Buckit,

Thank you for posting your code, as I am sure it will help many people who are using an older version of PHP that can't use filters.
Wow, grumpy much? "thinly veiled slights", "flame others"? Seeing that you just got here, you must not have seen any of my other posts, so excuse me if I occasionally make a mildly sarcastic comment meant in the friendliest of ways. Hopefully Buckit didn't take this as a "slight" or "flame". You should self moderate the way you're going off half-cocked or risk alienating yourself from this resource. :drunk:
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
buckit
Forum Contributor
Posts: 169
Joined: Fri Jan 01, 2010 10:21 am

Re: Email validation - regular expression

Post by buckit »

no offense taken by me! I am using the latest version of PHP so I am now updating my function with the one you posted above!

and I learned something here... there is something called filters thats new(ish) to PHP! something for me to lookup and apply!

Everything I know about PHP (only started using it 8months ago) is from Google. I only recently started contributing to this forum because I noticed I knew some answers to questions or at least thought I could provide valid input to maybe help others out! Hopefully I am actually helping! :)

anyway! Thanks for your post AbraCadaver! I'll definitely be able to learn something from that function that I can apply elsewhere!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Email validation - regular expression

Post by AbraCadaver »

buckit wrote:no offense taken by me! I am using the latest version of PHP so I am now updating my function with the one you posted above!

and I learned something here... there is something called filters thats new(ish) to PHP! something for me to lookup and apply!

Everything I know about PHP (only started using it 8months ago) is from Google. I only recently started contributing to this forum because I noticed I knew some answers to questions or at least thought I could provide valid input to maybe help others out! Hopefully I am actually helping! :)

anyway! Thanks for your post AbraCadaver! I'll definitely be able to learn something from that function that I can apply elsewhere!
Good to know, thanks for replying. After viewing your reply I looked back at my code and saw that it could be shortened (slightly): :wink:

Code: Select all

function validEmail($email) {
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
                list($name, $domain) = explode('@', $email);
                return getmxrr($domain);
        }
        return false;
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
MichaelR
Forum Contributor
Posts: 148
Joined: Sat Jan 03, 2009 3:27 pm

Re: Email validation - regular expression

Post by MichaelR »

Here's the regular expression used by filter_var() when using FILTER_VALIDATE_EMAIL:

Code: Select all

'/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/i'
So use that if you don't have the newest version(s) of PHP.
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

Re: Email validation - regular expression

Post by shawngoldw »

I've been using this regex:
!^([a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*@[a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*\.[a-zA-Z]{2,4})+$!

It is much simpler and if it's supposed to be that complicated, mine must fail somewhere. Anyone wanna tell me where? :wink:

Shawn
MichaelR
Forum Contributor
Posts: 148
Joined: Sat Jan 03, 2009 3:27 pm

Re: Email validation - regular expression

Post by MichaelR »

shawngoldw: it doesn't limit length, doesn't allow the full range of dot-atom text, doesn't allow a quoted string or obsolete local-part, doesn't allow domain literals, wrongly allows consecutive hyphens in the domain name, doesn't allow internationalized domain names, wrongly allows a domain label to begin and/or end with a hyphen, disallows some TLDs, and allows underscores in the domain name.
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

Re: Email validation - regular expression

Post by shawngoldw »

MichaelR wrote:shawngoldw: it doesn't limit length, doesn't allow the full range of dot-atom text, doesn't allow a quoted string or obsolete local-part, doesn't allow domain literals, wrongly allows consecutive hyphens in the domain name, doesn't allow internationalized domain names, wrongly allows a domain label to begin and/or end with a hyphen, disallows some TLDs, and allows underscores in the domain name.
Thank you, I really appreciate that comprehensive list.
MichaelR
Forum Contributor
Posts: 148
Joined: Sat Jan 03, 2009 3:27 pm

Re: Email validation - regular expression

Post by MichaelR »

Oh, and it allows the following characters in the domain name (and also in the local-part, some (but not all) of which are illegal characters):

: ; < = > ? @ [ \ ] ^

If you want a very basic one, use this:

Code: Select all

/^(?!.{255,})(?!.{65,}@)(?:[a-z0-9_-]+(?:\.[a-z0-9_-]+)*)@(?:[a-z0-9]+(?:-[a-z0-9]+)*\.){1,}[a-z]{2,6}$/i
Post Reply