USA’s Zip Code Validation in PHP

Posted on March 20, 2008 
Filed Under how-to, php, tutorial

My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I came to this solution.

The valid format of zip code of USA might be a five digit number like “12345” or in the format of 4 digit followed by first 5 digits like “12345-5434“.And, we need a function to validate the both kind of format of zip code.

Here is the function,

function validateUSAZip($zip_code)
{
  if(preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code))
    return true;
  else
    return false;
}

Now, let’s look at the explanation of the regular expression used in this function. A perl regular expression always starts with “/” and ends with “/” and “i” after closing “/” refers that the expression is “case insensitive”.As you know, “^” refers that, it is the beginning of the expression. And, the expression “([0-9]{5})” tells that there should be exactly 5 digits at the beginning of the expression. Furthermore, the second expression “(-[0-9]{4})“, means that after first 5 digit there should be another 4 digit followed by the “-” sign.The “?” sign next to second expression tells that the second expression is optional.And finally, the “$” sign before “/i” refers that it is the end of the expression.

Popularity: 7% [?]

Enter your email address and get recent tutorials, tips, tricks and scripts of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Follow me on twitter at http://twitter.com/roshanbh.

Related Posts

» Date format validation in PHP
» Ip address validation in PHP using regular expression
» USA’s phone number validation using Regular expression in PHP
» Canada’s postal code validation in PHP

Comments

4 Responses to “USA’s Zip Code Validation in PHP”

  1. PHP Coding School » Blog Archive » php tips [2008-03-20 18:59:04] on March 20th, 2008 7:04 pm

    [...] USA’s Zip Code Validation in PHP By Roshan My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I came to this solution. Roshan Bhattarai’s Blog - PHP… - http://roshanbh.com.np [...]

  2. Denny on June 9th, 2008 2:05 pm

    Why not simplify?

    function validateUSAZip($zip_code) {
    return preg_match(”/^([0-9]{5})(-[0-9]{4})?$/i”,$zip_code);
    }

  3. Roshan on June 9th, 2008 3:44 pm

    ya denny you can surely simply the above function like this…

  4. smithveg on July 21st, 2008 7:07 am

    Good, Thank for your quote.
    That’s pretty easy to integrate and use.

Leave a Reply