Form and Spelling Validation -
(Page 4 of 14 )
Zip codes and postal codes can be an atrocious to validate. Each country has its own system of postal codes. For the purposes of this lesson, we will examine how to validate US zip codes and Canadian postal codes. Many other countries follow the same format as the US and Canada does. Other places, such as the United Kingdom, have very different formats.
The function we are about to examine for zip and postal code validation is written in such a way that other countries can be plugged into it, so that we can expand on the function if the need arises.
US zip codes come in two different flavors, a standard zip code that is five digits or zip+4 which is 5 digits, a hyphen, and then 4 more digits. We will account for both of these possibilities. The first thing we will do with any zip code passed to the function is to remove all spaces and hyphens. This will allow us to examine the zip code without worrying if the user included a hyphen or a space. The next step in validating the US zip code is to check its length. Acceptable lengths would be five or nine digits once spaces and hyphens are removed. Any zip code that does not meet the length standard will not validate. The final check will be to make sure that the zip code only contains digits. For this, we will use the isDigits() function from the previous section.
Validating Canadian postal codes follows a similar route as the US zip code. First, all spaces or hyphens will be removed and then the length of the postal code will be examined. A Canadian postal code should always be six characters in length. After the length check, we will check to make sure the postal code fits the proper pattern. The postal code should consist of three sets of a letter followed by a number.
Now, let's look at the function we will use to accomplish the validation.
<?php function checkMailCode($code, $country) { $code = preg_replace("/[\s|-]/", "", $code); $length = strlen ($code);
switch (strtoupper ($country)) { case 'US': if (($length <> 5) && ($length <> 9)) { return FALSE; } return isDigits($code); case 'CA': if ($length <> 6) { return FALSE; } return preg_match ("/([A-z][0-9]){3}/", $code); } } ?> |
The great thing about the structure of this function is that if you need to validate other countries, you can drop the routines for them right into it with little hassle. Another method of expanding this function is to just add cases for countries that already match one of the existing ones. For example, Mexico used a five-digit zip code like the US. To add Mexico to this function, you would only need to add one line, directly under the case for the US.
<?php switch (strtoupper ($country)) { case 'US': case 'MX': if (($length <> 5) && ($length <> 9)) { ?> |
Next: >>
More Miscellaneous Articles
More By Matt Wade