Tuesday, June 3, 2014

Validate Email address using php built-in function

Use the filter_var() function.

A common task your web app might need to do is to check if a user has entered a valid email address. You'll no doubt find online a dizzying range of complex regular expressions that all claim to solve this problem, but the easiest way is to use PHP's built-in filter_var() function, which can validate email addresses.

Example

?
1
2
3
4
<?php
filter_var('sgamgee@example.com', FILTER_VALIDATE_EMAIL); // Returns "sgamgee@example.com". This is a valid email address.
filter_var('sauron@mordor', FILTER_VALIDATE_EMAIL); // Returns boolean false! This is *not* a valid email address.
?>

Further reading