PHP Email Validation Tutorial

Ranked #2,130 in Internet, #124,885 overall

Validate user's email input

In this tutorial we'll create a script to validate emails from user input. We will assume the user input has been saved in a variable $email. Now we'll create a validation function that checks whether the user input stored inside the variable is a valid email. This tutorial does not require a lot of pre-knowledge, beside some PHP basics knowledge ( about variables, functions ) and some understanding of regular expressions in PHP might come handy ( however it will be explained inside of this tutorial as well ). Let's get started!

What is a valid email?

When can an email provided by a user, be called 'valid'?

Before we can write a validation function for validating emails, we need to think of a definition of a valid email. Which is not that hard, in general we could say an email should be structured like this:

user@provider.lan

Where 'user' and 'provider' can be any string containing alphabetical characters, numbers and undercores. However we cannot be sure this way whether the 'provider.lan' provided, would be a valid one. For example:

someuser@a4g98si3m.x0a

would match our requirements for a valid email (if we used the definement as mentioned above ). However if we defined that 'provider' should be one out of a list ( for example: "hotmail | live | gmail" ) we might find ourself rejecting a valid email with a provider which we don't have in our list of valid ones but which does exist. Therefore, in this tutorial, I'll show 2 ways to validate an email: the 'rough' way ( which just requires the email to be like the first format ) and the more 'precise' way ( by specifying the providers that are valid ). Let's first create a validation pattern for a simple email validation.

Note: of course it's also a possibility to actually use the php mail function to send an email to the email provided, and this way verify whether the email was correct. But that's probably not the desired method here, and we'll here discuss only the regular expressions matching method.

Email Validation Pattern #1

As we've seen above, a valid email could be (simplified) defined as:

[alphabetical, numeric characters or (under)cores, dots]@[alphabetical, numeric characters or undercores].[alphabetical, numeric characters]

Which is in regular expressions:

^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9]+$

Where ^ defines the start and $ the end of the string ( email ). Between brackets we put the characters allowed and behind the brackets we put the amount of times a character from this selection may occur (+ = atleast once). Since a dot is a special regular expression sign, we have to escape it by putting a backslash before it ( this way it's seen as a litteral character and not a sign with any meaning ). The same goes for the - and @ signs.

If we want the extension of the email to be atleast 2 and max 4 characters long, the pattern would be:

^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9]{2-4}$

Another posibility for validating the 'extension' of the email (.com/.net/etc.) would be to match it with a list of valid ones. For example:

^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.(com|net|org|nl|uk)$

which would allow all emails with .com, .net, .org, .nl and .uk extensions, while our previous regular expression would allow any extension ( also invalid ones ).

Email Validation Pattern #2

It's also possible to define a list of valid providers with which the email's provider should match. We can do this the same way as we've done it for the email extensions:

^[A-Za-z0-9_\-\.]+\@[hotmail|live|gmail]+\.(com|net|org|nl|uk)$

However this way the combination of an email provider and extension does not matter. For example: gmail.com would be valid, but also gmail.net. We don't actually want this and therefore we'll combine them (only allowing valid combinations of email provider and extension):

^[A-Za-z0-9_\-\.]+\@(hotmail\.com|live\.nl|gmail\.com)$

Usage Examples

Now we've created 2 types of patterns for the email validation (ending up in about 3 or 4 different patterns). We can now use these patterns to match an email using the PHP built-in function called preg_match. In this example we'll use the first pattern we created for validating an email (the simple one) but you can replace it with any of the patterns we created in this tutorial ( up to your preferance ).

<?php
//define the email validation pattern
$pattern = "^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9]+$";

//define a test email to validate
$email = "valid-email1@hotmail.com";
//validate the email
if(preg_match("/{$pattern}/", $email)) {
echo "<p>{$email} is a valid email.</p>";
}else{
echo "<p>{$email} is an invalid email.</p>";
}

$email = "invalid'email@abc.com";
if(preg_match("/{$pattern}/", $email)) {
echo "<p>{$email} is a valid email.</p>";
}else{
echo "<p>{$email} is an invalid email.</p>";
}

$email = "anotherinvalidemial@something";
if(preg_match("/{$pattern}/", $email)) {
echo "<p>{$email} is a valid email.</p>";
}else{
echo "<p>{$email} is an invalid email.</p>";
}
?>

This could also be created into a simple small function:

<?php
function validateEmail($email) {
$pattern = "^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9]+$";
if(preg_match("/{$pattern}/", $email)) {
return TRUE;
}else{
return FALSE;
}
}
?>

Note: To use one of the other patterns we created in this lens ( the more precise ones ) and edit them to your likes, is also possible. Then just replace the simplefied pattern in the code with the more precise pattern we created last.

Next PHP Tutorial

Loading poll. Please Wait...

You might also like ...

Loading

Comments & Questions

Got any questions about the tutorial or just want to comment? This is the place to do so.

  • Ole Feb 15, 2012 @ 8:13 am | delete
    Or you could just use idn_to_ascii that was added in 5.3.0 which turns it into proper punycode. I'll add the links for refference :)

    http://en.wikipedia.org/wiki/Punycode
    http://no2.php.net/manual/en/function.idn-to-ascii.php
  • Ole Feb 9, 2012 @ 5:34 pm | delete
    What about IDN? Domains are not restricted to a-z, but also contain multi-byte.
  • webcodez Feb 13, 2012 @ 5:30 pm | delete
    Yes that's right. For that you'd need to alter the pattern to your likes. However the patterns in this tutorial can be used for all the mayor domains email addresses.
  • Bonzlee Jun 20, 2011 @ 10:12 pm | delete
    Great lens! I'm a Joomla enthusiast but not a PHP coder but always wanted to learn. I usually have to hire a develoeper to help. I'm looking forward to learning along with you as you build your lenses.
  • webcodez Jun 21, 2011 @ 3:51 am | delete
    That's great to hear! I hope my lenses can help beginning coders who never got to learn PHP to actually learn it and I'm glad to hear you like my lenses. I hope they'll help you learn PHP and if you've got any questions about any of my tutorials, just let me know and I'd be glad to help.

Related Products (Amazon)

Loading

Related Products (eBay)

Loading

by

webcodez

"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."

webcodez
GameHeroes
more »

Feeling creative? Create a Lens!