| Subcribe via RSS

Validate Email Address

February 23rd, 2007 Posted in PHP

Here's some PHP code that will validate an email address.

PHP:
  1. <?php
  2. function validEmail($email_address){
  3.     // First, we check that there's one @ symbol, and that the lengths are right
  4.     if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email_address)) {
  5.         // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  6.         return false;
  7.     }
  8.     // Split it into sections to make life easier
  9.     $email_array = explode("@", $email_address);
  10.     $local_array = explode(".", $email_array[0]);
  11.     for ($i = 0; $i <sizeof($local_array); $i++) {
  12.         if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  13.             return false;
  14.         }
  15.     }
  16.     if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  17.         $domain_array = explode(".", $email_array[1]);
  18.         if (sizeof($domain_array) <2) {
  19.             return false; // Not enough parts to domain
  20.         }
  21.         for ($i = 0; $i <sizeof($domain_array); $i++) {
  22.             if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  23.                 return false;
  24.             }
  25.         }
  26.     }
  27.     return true;
  28. }
  29. ?>

Leave a Reply

Preview: