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% [?]
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”
Leave a Reply






[...] 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 [...]
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.