USA’s Zip Code Validation in PHP
- Thursday, March 20, 2008, 18:08
- how-to, php, tutorial
- 6 comments
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: 8% [?]
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






Why not simplify?
function validateUSAZip($zip_code) {
return preg_match(”/^([0-9]{5})(-[0-9]{4})?$/i”,$zip_code);
}
ya denny you can surely simply the above function like this…
Good, Thank for your quote.
That’s pretty easy to integrate and use.
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.
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.
http://www.zipcodeworld.com/zipcodefree.htm