Duminda Chamara

Tuesday, March 15, 2011

How to validate email address in php

How to validate an email address in php?


Following example shows you how to validate an email address using PHP.


When creating online registration forms, you may need to validate user inputs. It is a good practice validate user inputs before submit the form. You can use JavaScript to validate user inputs as client-side validation. But in some cases users may have disabled execution of JavaScripts on there browsers. In such cases it is very important to use server side validate mechanism to validate user inputs, because user can't by-pass server-side validation. You can validate an email address in two ways using PHP.

  1. Validate email using Regular Expression
  2. Validate email address using filter_var() built-in php function
In HTML version 5, there is an input type called 'email'. This email input field can validate email address before user submit the form. This is browser-built-in email validation mechanism. But Old browsers which does not support rendering HTML-5 cannot understand this email input field. So please be careful using this email input in your web forms. Following example shows you how to validate an email address using PHP as server-side validation.

1. Validate an email address using regular expression with php.

PHP Code

function validateEmailAddressUsingRegularExpression($emailAddress){ $regularExpression='/^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/'; if (preg_match($regularExpression,$emailAddress)) { return true; }else{ return false; } }

$emailAddress='someone@gmail.com';

if(validateEmailAddressUsingRegularExpression($emailAddress)==false){ echo 'Email address in invalid'; }else{ echo 'Email address is valid'; }

2. Validate an email address using filter_var() function in php.

PHP Code

function validateEmailAddressUsingFiltervar($email_address){ if(!filter_var($email_address, FILTER_VALIDATE_EMAIL)){ return true; }else{ return false; } }

$emailAddress='someone@gmail.com';

if(validateEmailAddressUsingFiltervar($emailAddress)==false){ echo 'Email address in invalid'; }else{ echo 'Email address is valid'; }

©-Copyright By Duminda Chamara JavaScript Validation