Email Validation
Want to check a user has entered the correct email into a form? heres how...
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.
First, we have to know the format of an email.
- The Beginning of the string
- The first character cannot be a @ or a space
- And that character is repeated any number of times
- Then there is an @ (at)
- After the @ (at) is a character that cannot be a @ (at) or a space
- Then a character repeated any number of times
- A period
- One character that is not a @ (at) or a space
- Which is repeated any number of times
- 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:
I hope you like this one too :D
<?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
This tutorial was by Adman, brought to you by Robouk, please post any questions in the forum. Thank you.