Sunday, October 10, 2010

PHP Filter - email validation

For PHP5, you can validate email format as below:

$email = 'testemail@xxx.com';  
  
if( filter_var($email, FILTER_VALIDATE_EMAIL) )  
 echo 'Valid email format!';  
else  
 echo 'Invalid email format!'; 

For PHP version less than 5.0, you have to use regular expression to validate email format.

$email = 'testemail@xxx.com';  
  
if( eregi('^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$', $email) ) 
 echo 'Valid email format!';  
else  
 echo 'Invalid email format!'; 


For reference:

You can found out more build-in validates at php.net each as URL, IP validation which are very useful.
http://php.net/manual/en/filter.filters.validate.php