Ideal way to perform email validation in php

I found this email validation function while working in ActiveCollab. By default, this function uses PHP’s inbuilt filter_var function to validate email, which is supported in PHP 5 (> 5.2.0). If version of PHP is older (is less than 5.2.0) it will use preg_match function to validate email using matching pattern defined as a constant here named EMAIL_FORMAT.

[php]function is_valid_email($user_email) {
if(function_exists(‘filter_var’)) {
return filter_var($user_email, FILTER_VALIDATE_EMAIL);
} else {
if(strstr($user_email, ‘@’) && strstr($user_email, ‘.’)) {
define(‘EMAIL_FORMAT’, "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i");
return (boolean) preg_match(EMAIL_FORMAT, $user_email);
} // if
} // if
return false;
} // end func is_valid_email[/php]

It is worth noting that, before passing string to preg_match to process the validation this function checks for the presence of @ and dot (.) operators which is really good and recommended approach not just in the context of validation of email but it does show that how one can save small bits of memory and time here and there which eventually may lead to big savings while building large and high traffic applications.

Leave a Reply

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