Regular expressions for data validation

Regular expressions for testing validity

Phone numbers in this format: 999-999-9999

      /^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}$/
      

Credit card numbers in this format: 9999-9999-9999-9999

       /^[[:digit:]]{4}(-[[:digit:]]{4}){3}$/ 
      

Zip codes in either of these formats:

      99999 or 99999-9999 /^[[:digit:]]{5}(-[[:digit:]]{4})?$/ 
      

Dates in this format: mm/dd/yyyy

      /^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][[:digit:]]|3[01])\/[[:digit:]]{4}$/
      

Test a phone number for validity

      $phone = '559-555-6624';  // Valid phone number
      $phone_pattern = '/^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}$/'; 
      $match = preg_match($phone_pattern, $phone); // Returns 1
      

Test a date for a valid format, but not for a valid month, day, and year

      $date = '8/10/209'; // Invalid date
      $date_pattern = '/^(0?[1-9]|1[0-2])\/' . '(0?[1-9]|[12][[:digit:]]|3[01])\/' . '[[:digit:]]{4}$/'; 
      $match = preg_match($date_pattern, $date); // Returns 0
      

A function that does a complete validation of an email address

      function valid_email ($email) { 
        $parts = explode("@", $email); 
        if (count($parts) != 2 ) {
          return false;
        }
        if (strlen($parts[0]) > 64) {
          return false;
        }
        if (strlen($parts[1]) > 255) {
          return false; 
        }
        $atom = '[[:alnum:]_!#$%&\'*+\/=?^`{|}~-]+'; 
        $dotatom = '(\.' . $atom . ')*'; 
        $address = '(^' . $atom . $dotatom . '$)'; 
        $char = '([^\\\\"])'; $esc = '(\\\\[\\\\"])'; 
        $text = '(' . $char . '|' . $esc . ')+'; 
        $quoted = '(^"' . $text . '"$)'; 
        $local_part = '/' . $address . '|' . $quoted . '/'; 
        $local_match = preg_match($local_part, $parts[0]); 
        if ($local_match === false || $local_match != 1) {
          return false; 
        }
        $hostname = '([[:alnum:]]([-[:alnum:]]{0,62}[[:alnum:]])?)'; 
        $hostnames = '(' . $hostname . '(\.' . $hostname . ')*)'; 
        $top = '\.[[:alnum:]]{2,6}'; 
        $domain_part = '/^' . $hostnames . $top . '$/'; 
        $domain_match = preg_match($domain_part, $parts[1]); 
        if ($domain_match === false || $domain_match != 1) {
          return false; 
        }
        return true; 
      }
      

Back