PHP: How to validate e-mail addresses using regular expressions

Posted on May 21, 2008, under PHP,  Bookmark it

This function checks if an email address is valid or not. For example it is very useful if you have to validate a HTML form where someone should enter a real email address.

function ValidateEmail($email)
{
/*
(Name) Letters, Numbers, Dots, Hyphens and Underscores
(@ sign)
(Domain) (with possible subdomain(s) ).
Contains only letters, numbers, dots and hyphens (up to 255 characters)
(. sign)
(Extension) Letters only (up to 10 (can be increased in the future) characters)
*/

$regex = '/([a-z0-9_.-]+)'. # name

'@'. # at

'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains

'.'. # period

'([a-z]+){2,10}/i'; # domain extension 

if($email == '') {
	return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}

return empty($eregi) ? true : false;
}

$email = 'name@domain.com'; 

// will return true, since it matches the regex

if(ValidateEmail($email))
{
echo ''.$email.' is a valid e-mail address.';
}
else
{
echo ''.$email.' is not a valid e-mail address.';
}

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Related Posts

2 Replies to "PHP: How to validate e-mail addresses using regular expressions"

  1. What about the .museum domains? They will fail your regex. This is just a simple validation, will not work for all valid emails out there.

  2. Yes, you are right. Thanks for the tip. The regex has been updated. I hope that’s OK now. The extension can have up to 10 characters.

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)