Validating UK postcodes with Visual FoxPro

2011-08-19

Postcodes in the UK do much more than mailsort. They are widely used to link individuals to various types of geographical, demographic and marketing data, and it's especially important that they are recorded and processed accurately. Thus, if your application processes UK postcodes, you'll need an effective way of validating them.

UK postcodes follow strict formatting rules. If you don't have access to the PAF, you can at least check that the postcodes in your application follow these rules. In this article, we offer a Visual FoxPro function that does just that.

This function is currently available with PHP, Javascript, Visual Foxpro. If you want to share this function in other languages, please contact us.

checkPostcode function

Remember, postcode validation function below only checks that the code is in the correct format. A code might pass this test but still not be a genuine postcode. To determine whether a postcode actually exists, you would need to access the Postcode Address File. (But even that wouldn't be a perfect check, as the PAF is never completely up to date, postcodes are constantly being added, and existing premises are occasionally re-coded. Also, Royal Mail acknowledges that the PAF contains errors.)

FUNCTION CheckPostcode
* Checks that a UK postcode is syntactically valid. 
* The code must be all caps, and must include a space
* between the inward and outward portions (multiple
* spaces are allowed).
LPARAMETERS tcCode
LOCAL lcTest, lcInLetters, lcInward, lcOutward
tcCode = ALLTRIM(tcCode)

* Check for the space
IF SUBSTR(tcCode, LEN(tcCode)-3, 1) <> " "
  RETURN .F.
ENDIF 

* Create a string in which all the capital letters 
* in the code are represented as A, all the digits 
* as 9, and all other characters remain unchanged.
lcTest = ;
  CHRTRAN(tcCode, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", ;
  REPLICATE("A", 26))
lcTest = ;
  CHRTRAN(lcTest, "0123456789", ;
  REPLICATE("9", 10))

* Separate out the test string into outward and 
* inward portions
lcOutward = ALLTRIM(LEFT(lcTest, LEN(tcCode)-4))
lcInward = RIGHT(lcTest, 3)

* The inward portion must be in the format 9AA
IF lcInward <> "9AA"
  RETURN .F.
ENDIF

* Certain letters disallowed in the inward portion
lcInLetters = RIGHT(tcCode, 2)
IF lcInLetters <>  CHRTRAN(lcInLetters, "CIKMOV", "")
  RETURN .F.
ENDIF

* The outward portion must be in one of the 
* following formats:
* A9, AA9, A99, AA99, A9A, AA9A
IF NOT INLIST(lcOutward, ;
  "A9", "AA9", "A99", "AA99", "A9A", "AA9A")
  RETURN .F.
ENDIF
RETURN .T.
ENDFUNC

Download

Click to download above scripts (892 bytes).