How to validate email address format in PHP?

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

You need to validate email address format in PHP whenever user enters an email in a form.  If you are building a contact form, this is essential in order to prevent form hijacking.

To validate an email in PHP, you can do something like …

validate email in PHP

validate email in PHP

To try out, you can construct page with form that submit to same page.

PHP does all the work really.  Because filter_var is a PHP function.  And when used in conjunction with the PHP constant FILTER_VALIDATE_EMAIL, it will make sure that the first parameter is a valid email.

If not valid email is supplied, filter_var will return an empty string.  Because it has filtered out bad inputs.   In PHP an empty string is considered false.  So the negative of that throws us into the first if-clause saying not valid email.

If a valid email is supplied, filter_var will return that email.  It returns an non-empty string (considered true in PHP).

Test with values like …

test@example.com
TEst@eXample.net

and it shows valid.

Test with values like …

test@example.com test@example.net

test@example.com,test@example.net

test@.com

test@example

testexample

and it all return invalid.