A very common task when building Web sites involves validating user-supplied e-mail addresses. In this article we'll show you how to use the powerful regular expression engine built into PHP.

A very common task when building Web sites involves validating user-supplied e-mail addresses. This is of particular importance to sites which require a valid e-mail address for transactions -- e-commerce sites, Web mail sites, mailing lists and so on.

If your Web site uses PHP, however, you're in luck. It's extremely easy to validate user supplied e-mail addresses in PHP, thanks largely to a very powerful regular expression engine built into the language. In this article, I'll demonstrate how easy it is.

To begin, assume you have the following Web form, which asks the user to enter an e-mail address.

<html>
<head></head>
<body>
<form action="validate.php" method="post">
Enter e-mail address: <input type="text" name="e-mail">
</body>
</html>

As the code above shows, this form is submitted to the PHP script validate.php. Assuming the e-mail address is an important input into the next transaction, it's very important to verify that it is valid before using it.

The best way to accomplish this is with a regular expression, which checks the format of the e-mail address and ensures that it conforms to the standard format of user@domain.ext. Here's an example:

<?php
// check e-mail address
// display success or failure message
if (!preg_match("/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/", $_POST['email']))
{
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
?>
}

Try it for yourself and see. The script will flag all e-mail addresses that are not in the format user@domain.ext. This is accomplished with the regular expression /^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0- 9_-]+)+/. Let's look at each bit of it in detail:

* The caret (^) indicates the beginning of the string.

* The expression ([a-zA-Z0-9])+ indicates the range of allowed characters for the user part of the e-mail address. The plus (+) symbol appended to the end of this range indicates that at least one character from this range is mandatory.

* The @ symbol is exactly what it looks like -- the literal @ symbol used in an e-mail address.

* The expression ([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+ represents the domain.ext part of the e-mail address. Notice that the first range does not include a period (.), while the second one does. This is to ensure that the domain part of the address contains at least one character. Again, the plus(+) symbols scattered throughout the pattern indicate that at least one valid character is required.

Of course, this expression isn't perfectâ€"it will fail on addresses in the format first.last@domain.ext, and pass invalid domain extensions. You can tighten up the regular expression a little, by allowing periods in the username part and restricting the length of the domain extension. Here's an example:

<?php
// check e-mail address
// display success or failure message
if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-
]+)*\.([a-zA-Z]{2,6})$/", $_POST['e-mail'])) {
die("Invalid e-mail address");
echo "Valid e-mail address, processing...";
?>

Some of the interesting enhancements here are:

* The username part of the e-mail address now has two ranges, one containing alphabetic, numeric and dash characters and the other also supporting periods (.). This allows usernames of the form first.last@domain.ext.

* The extension part of the e-mail address, ([a-zA-Z]{2,6}), now has a size specifier enclosed in curly braces. This forces the extension to be between 2 and 6 characters long. All currently valid domain extensions fall within this range.

Caution: Obviously, this restriction, while reducing the incidence of too-long or too-short domain extensions, doesn't solve the problem entirely; users can still input invalid extensions between 2-6 characters long. This can be rectified by replacing the final part of the expression with a rigid list of valid domains (it hasn't been done here because it significantly increases the length and processing efficiency of the expression).

* The dollar ($) symbol is the end-of-string delimiter.

These are just two examples of regular expressions you can use to validate e-mail addresses. Many more variants exist, each with its own advantages and drawbacks. Remember that, given efficiency constraints, no pattern is completely foolproof, and so you should choose a pattern that has an appropriate combination of rigidity and performance for your needs. Happy coding!

Do you need help with PHP? Gain advice from Builder AU forums

Related links

Comments

1

Ian Eiloart - 29/11/05

The author clearly has no idea of what is and is not permitted in an email address. This routine will fail to validate a huge number of email addresses. It even fails to validate some domains. There are dozens of similar php articles out there, mostly making the same mistakes.

» Report offensive content

2

Sean Coates - 29/11/05

The problem of validating an email address is not a simple one. As the article indicates: these patterns are not foolproof.

In fact, you'd be better off NOT validating an email address than simply using one of the patterns in this article.

Proper email validation can be found here: http://examples.oreilly.com/regex/email-opt.pl

Warning, though: the regex it generates is around 28 kilobytes.

» Report offensive content

3

PHP Developer - 07/08/06

If there is a solution why has nobody posted it?

Most of us need only simple but useful and secure solutions like can be a secure and seriouse mail validation system, why is this so immpossible to have?

I believe in PHP and I like it and I think that I'm not going to learn PERL to validate my visitors' e-mails.

Can somebody finaly write down a seriouse article about how to make a e-mail validator in PHP that is secure and "ALMOST" universal???

This will be a greate thing.

Besides e-mail validation the "preg_match" function is amlost an undocumented function on www.php.net.
There is not way to understand how to make your CUSTOM validator??

If you go to:
http://it.php.net/manual/en/function.preg-match.php
you can found almost everithing from validating russians characters to validate aliens from Alpha Centaury users but not a valid e-mail validator.

If you guys made it first (http://www.builderau.com.au) you will be the first and it will be really a great thing how to drive more visitors to your PHP section.

Besides all comments and maybe ironic style thank you for your article, I funund it very usefull ;)

» Report offensive content

4

Nigel Milligan - 09/12/06

No Help Whatsoever I'm afraid, didn't work at all!!
Not happy!!

» Report offensive content

5

Ben - 15/03/07

The apostrophe is commonly used as part of the email username, such as paddy.o'mally@oirish.ie, which this parser wouldn't allow.

Before writing an article like this, it would be a big help to be more familiar with the syntax of email addresses.

Sean has a point in not using a validator at all. If a valid email address is critical, it's probably more effective to ask the user to enter an email address twice in the form and to simply check that the values are identical.

After all, a typo won't necessarily invalidate an email address anyway.

» Report offensive content

6

James - 10/05/07

Very useful info here! Much appreciated, wish I could get the grasp of reg expressions!!!!!

» Report offensive content

7

Matthew berg - 07/06/07

Not only does your validator fail to account for a number of permissable characters (!#$%

» Report offensive content

8

Matthew Berg - 07/06/07

Not only does your validator fail to account for a number of permissable characters (!#$%

» Report offensive content

9

GHJKL - 04/12/07

10

Matjaz - 20/01/08

Thanks. Nice tutorial, i will integrated it in my guestbook. :-)

» Report offensive content

11

serginho - 22/05/08

we can find an example in wordpress code : wp-includes/formatting.php

(:-)> & :O=="

function is_email($user_email) {
$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
if (preg_match($chars, $user_email)) {
return true;
} else {
return false;
}
} else {
return false;
}
}

» Report offensive content

12

kanika - 05/09/08

Does anyone know how to validate an email address with an apostrophe??
Its really urgent.....

Thamks.

» Report offensive content

13

phani - 17/09/08

i don't need validate for plus(+) symbol in email validation can any body help me.........

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

13

phani - 17/09/08

i don't need validate for plus(+) symbol in email validation can any body help me......... ... more

12

kanika - 09/05/08

Does anyone know how to validate an email address with an apostrophe?? Its really urgent..... Thamks. ... more

11

serginho - 22/05/08

we can find an example in wordpress code : wp-includes/formatting.php (:-)> & :O==" function is_email($user_email) { $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i"; if (strpos($user_email, '@') !== ... more

Log in


Sign up | Forgot your password?

  • Staff XP stays on life support for longer

    This week's Roundup looks at Microsoft's decision to extend the life of Windows XP, the release of Microsoft Surface SDK, Firefox's new Geode plug-in, Yahoo's new tool -- Smush It and more. Read more »

    -- posted by Staff

  • Chris Duckett The good and truly awful celluloid depictions of computers

    Ever wonder why your lawyer uncle leaves the room whenever you turn over to Boston Legal? Or why your forensic science cousin can't stand crime drama? You know the answer: it’s the horrid trivialisation and dumbing down of an occupation to make it appear entertaining. Sometimes it is so unbelievable that it actually hurts and yelling at the screen is the only outlet. Read more »

    -- posted by Chris Duckett

  • Brendon Chase Apple's iPhone engineers to tour Sydney, Melbourne

    Aussie developers will be able to get up close and personal with some of the iPhone engineers in November to learn how to build applications for the platform. Read more »

    -- posted by Brendon Chase

What's on?