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!
- May 21, 2008
- article by Gabriel C.
- 2 comments
Related Posts
-
PHP: Convert E-Mail Addresses from a String into Clickable Linksat October 6, 2008 with 2 comments
-
Validate (input) passwordat August 30, 2008 with 2 comments
-
How to extract domain name from an e-mail address stringat September 5, 2008 with 1 comment
-
Validate (input) usernameat August 29, 2008 with 2 comments
-
How to extract username from an e-mail address stringat September 5, 2008 with 2 comments

2 Replies to "PHP: How to validate e-mail addresses using regular expressions"
August 27, 2008 at 1:23 PM
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.
August 27, 2008 at 1:58 PM
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.