Site Navigation:

Home // Tutorials // PHP // Email Validation

Validating email address's

1
Most web site have scripts that let a user register for the web site and login. Most of these require them to enter their email, but what is the use of a incorrect email in their database? In this tutorial I will show you how to catch those incorrect emails using Regular Expressions.

First, we have to know the format of an email.

  1. The Beginning of the string
  2. The first character cannot be a @ or a space
  3. And that character is repeated any number of times
  4. Then there is an @ (at)
  5. After the @ (at) is a character that cannot be a @ (at) or a space
  6. Then a character repeated any number of times
  7. A period
  8. One character that is not a @ (at) or a space
  9. Which is repeated any number of times
  10. Then the end of the string
2
Now that we know the format, we need to write a Regular Expression. A regular expression matches a pattern in a string. Here is the one we will use. ^[^@ ]+@\.[^@ \.]+$. That alone does not check the email for correctness, we need to use ereg(), and place it into a user-defined function like this:

function EmailCheck($Email) {
$Checked = ereg("^[^@ ]+@\.[^@ \.]+$", $Email);
if($Checked) {
return true;
} else {
return false;
}
}

3
On the second line, use ereg with the arguments of the Regular Expression, then the string for it to check in. If it works, $Checked will be present. If the email is correct the function will return true or 0, if not it will return false. Here is how to check and email.

if(EmailCheck("Email to Check") == 0) {
echo "Check was unsuccessful.";
} else {
echo "Check was successful.";
}
4
The code above checks to see if the function returned 0 or true, and then give the results. Here is the final Code:

<?php

function EmailCheck($Email) {
$Checked = ereg("^[^@ ]+@\.[^@ \.]+$", $Email);
if($Checked) {
return true;
} else {
return false;
}
}
if(EmailCheck("z-team@attasdfa....bic...om") == 0) {
echo "Check was wrong";
} else {
echo "Check was successful";
}
?>


I hope you like this one too :D
spacer

This Tutorial was by Adman, Please post any questions in the forum. Thank you.
BACK TO TUTORIALS



Home Tutorials Free Stuff About Gallery Forum Links Contact

Copyright © Robouk 2001.

Dreamweaver®, Flash® and Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Hosted by Pixelcode - web design tutorials.