Practical Web Programming

Sunday, January 06, 2008

How to Check if Email Address is Valid in PHP

If your website is accepting email address as input, it is always wise to check of it's validity as some users, especially spammers, have a habit of inputing garbage text in email fields. If you don't check it, you end up saving invalid email.

The PHP funtion below checks for the validity of the email address passed to it.

PHP function
function isValidEmail($address)
{
return preg_match("/^[a-z0-9._\-]+[@]([a-z0-9\-]+[.])+([a-z]{2,4})\$/i",
$address);
}


Using the function
if(!isValidEmail($_POST["email_address"]))
echo "Please input a valid email address.";
else
echo "Your email is valid";

1 comments:

mash said...

The expression you are using would exclude many valid emails. I have to point out you can't truly validate an Email with a regular expression. See http://regexadvice.com/blogs/mash/archive/2004/07/15/314.aspx for more on this point.

Recent Post