How to validate an e-mail address

This is my first tutorial for PHP 🙂
I wrote it because at almost any project this is a “must have” function.
The function is very very simple, it receive as a parameter an e-mail address and it returns the result of the validation (true if the address is valid or false if it isn’t, simple enough 😉 ?).
So … how is this done? … using the EREGI PHP function (look at the end of the tutorial for links) which is a regular expression matcher. After about 35 minutes (I didn’t knew anything about the Regular Expression Syntax) I managed to get a working code for this.
(If you want to copy it use the (Show Plain Code link))

function CheckEmail($email)
{
if ( !eregi( "^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$" , $email))
return false;
else
return true;
}

How to use it? Just like a normal PHP function ….

$e = "test@test.com";
if (CheckEmail($e))
print "Valid E-Mail Address";
else
print "Invalid E-Mail Address";

I hope this will help someone, until the next tutorial .. take care 😀

Bibliography :

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.