USA’s Zip Code Validation in PHP

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)
    return true;
    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.

10 thoughts on “USA’s Zip Code Validation in PHP

  1. Denny

    Why not simplify?

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

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

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

  4. Chris

    But I don’t believe 00000 is a valid zip code, nor is 00123. Basically, a zip code can start with a zero, but if it does, the second digit cannot be zero.

  5. Tim

    Instead of matching the ZIP code using regular expression, you can download the latest US ZIP code database from the following page for free. You can load the list into a database for real time validation and it is the most accurate method.

  6. @Tim: Don’t forget to upgrade your database frequently, new Zip Codes are added each week / month šŸ˜‰

  7. Awesome it works fine

  8. Darn. I was hoping that the zipcode website linked in a previous post ( would allow you to create a link directly to the text/CSV file of the database so we could automatically update our databases with a script :(

    However, you are required to fill out a form and can only receive the database file through email.

Leave a Reply

Your email address will not be published. Required fields are marked *