Validating Email Addresses

Wednesday, April 1, 2009

The following script verifies that an email address mostly follows the rules outlined in RFC 2822. This won't prevent someone from entering a false (but RFCcompliant) email address such as dontbugmeman@nonexistentdomain.com, but it will catch some typos.

<?php
function is_email($email) {
 if (! preg_match( '/^[A-Za-z0-9!#$%&\'*+-/=?^_`{|}~]+@[A-Za-z0-9-]+(\.[AZa-z0-9-]+)+[A-Za-z]$/', $email)) {
            return false;
 } 
 else {
  return true;
 }
}
?>


This script uses regular expression to check whether the given email uses proper email characters (alphabetical, dots, dashes, slashes, and so on), an @ sign in the middle, and at least one dot-something on the end.

Hope it helps.

0 comments: