Tag Archives: Regex

Email Validation using PHP

In one of my recent project I was required to validate email address in PHP. There are many ways to do this but I like following two approaches very much for which I created two different functions:

I created a function isEmail which will validate the email address and return true or false as per validation result.

First Approach: Using Filter functions (http://in.php.net/manual/en/function.filter-var.php)

This is quite simple and straightforward way using filter_var method and FILTER_VALIDATE_EMAIL constant which works on PHP 5.2+

Here is the function definition:
<?php
function isEmail_FirstApproach($strEmail)
{
if(filter_var($strEmail, FILTER_VALIDATE_EMAIL))
{
return true;
}
return false;
}
?>

Second Approach: Using Regular Expression (http://in3.php.net/manual/en/function.preg-match.php)
Regular expression is extremely powerful and quite confusing tool. So use it cautiously 🙂
Note: This function validates emails very well but quite not fully functional will all kind of emails. For e.g. Gmail gives option to add ‘+’ sign in emails which will fail with this functions and so on. Anyways you can easily enhance it 🙂

Here is the function definition:

<?php
function isEmail_SecondApproach($strEmail)
{
$strPattern = “/^([a-z])([a-z0-9._])+([a-z0-9])\@([a-z0-9])*([a-z])+(-[a-z])*([a-z0-9])*(\.([a-z0-9])*([a-z])+(-[a-z])*([a-z0-9])*)+$/i”;

if(preg_match($strPattern, $strEmail))
{
return true;
}
return false;
}
?>

Now simply call these functions to use it’s functionality as follows:
<?php
$email = “abc@example.com”;

if(isEmail_FirstApproach($email))
echo “Valid Email”;
else
echo “Invalid Email”;

if(isEmail_SecondApproach($email))
echo “Valid Email”;
else
echo “Invalid Email”;
?>

Note: Validation results can be different for different email addresses as filter validation is quite liberal than my Regex function.

Let me know if you find any issue with this or know any more efficient way to perform the same.

Advertisements