Validating postcodes

Do not use code, components or techniques unless you are satisfied that they will work correctly in your applications. If your application processes UK postcodes, you'll need an effective way of validating them.

validating postcodes-47

Thus, SW1A is the outward code for parts of Westminster (SW1A 2AA, for example, is the prime minister's postcode).

To summarise, all valid postcodes match one of the following patterns (where A represents a letter, 9 a digit): There are a very few postcodes that don't follow the above rules, but most applications can safely ignore these.

Furthermore, the letters C, I, K, M, O and V never appear in the inward code (because they are easily confused with digits).

As for the outward code, this consists of either one or two letters, followed by either one or two digits.

Even if you never need to check UK postcodes, we hope you'll find the technique useful for other tasks.

By Mike Lewis If your database contains UK address data, it's especially important that the postcodes are correctly stored.

Feel free to copy and paste it into your application. lc Test = ; CHRTRAN(tc Code, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", ; REPLICATE("A", 26)) lc Test = ; CHRTRAN(lc Test, "0123456789", ; REPLICATE("9", 10)) * Separate out the test string into outward and * inward portions lc Outward = ALLTRIM(LEFT(lc Test, LEN(tc Code)-4)) lc Inward = RIGHT(lc Test, 3) * The inward portion must be in the format 9AA IF lc Inward CHRTRAN(lc In Letters, "CIKMOV", "") RETURN . ENDIF * The outward portion must be in one of the * following formats: * A9, AA9, A99, AA99, A9A, AA9A IF NOT INLIST(lc Outward, ; "A9", "AA9", "A99", "AA99", "A9A", "AA9A") RETURN . It then become an easy matter to test the code against a list of valid patterns.

To use it, simply call the Check Postcode function, passing the postcode as a parameter. This form of pattern matching can be applied to many other types of validation.

Such a table does exist (it's known as the Postcode Address File, or PAF).

But it contains over 27 million records, and is subject to strict licensing and copyright controls.

They include special codes for UK dependent territories (FIQQ 1ZZ for the Falkland Islands, for instance) and the code GIR 0AA, which is used by the National Girobank. Remember, our postcode validation function only checks that the code is in the correct format.

Tags: , ,