Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Friday, February 3, 2017

Server side email validation in php with filter_var

Validating email address on server side is more secure way to prevent from span entry, Some people disabled javascript on their browser and enter wrong or garbage username/email address, So validating email on server side is good approach.

You can use the filter_var() function, which gives you a lot of handy validation and more options.
Note: PHP 5.2.0 or higher is required for the filter_var function. Here is the quick function in php to validate email address in single line.
function checkValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
 
Above function will validate email like “chirag@gmail” as a valid email, In Standard HTML5 email validation also pass this string too as a valid email, You need to add some extra security in your function to validate TLS so that you can get more filtered email data.
Email with TLS validation.

function checkValidEmail($email){ 
   return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
}
 

Example:

echo checkValidEmail('chirag@gmail'); // false
echo checkValidEmail('chirag@gmail.'); // false  
echo checkValidEmail('chirag@gmail.com'); // true  
echo checkValidEmail('chirag@gmail.com.'); // false