How to validate an UK (United Kingdom) Post Code

I had a client, David, from UK and he asked me to build him a user management script so I accepted the job.
When it came to validation I was, at first, intrigued by their post code system (here,in my country, it is very simple : 6 digits, ex : 505200 ) but after I read some documents the UK system was also very simple :) .
The accepted formats are :

Format Example
AN NAA M1 1AA
ANN NAA M60 1NW
AAN NAA CR2 6XH
AANN NAA DN55 1PT
ANA NAA W1A 1HQ
AANA NAA EC1A 1BB
A=A to Z, N = 0 to 9

Besides this table there is an exception : GIR 0AA, a Postcode that was issued historically.
So, a function to do this validation will need to take in consideration that the user may or may not insert the space/s so the first thing needed to be done is to strip the spaces from the input parameter. The next step is to see if we have a match using the preg_match function and then return the result (true or false).

(If you want to copy it use the (Show Plain Code link))

  1. function IsPostcode($postcode)
  2. {
  3. $postcode = strtoupper(str_replace(‘ ‘,,$postcode));
  4. if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
  5. return true;
  6. else
  7. return false;
  8. }

How to use it? Just like a normal PHP function ….

  1. $e = "AB235RB";
  2. if (IsPostcode($e))
  3. print "Valid Post Code";
  4. else
  5. print "Invalid Post Code";

Bibliography :

2 Comments

  1. Nigel Johnson says:

    The data standards catalog entry shows that there are some exclusions to letters in certain positions, for example The letters Q, V and X are not used in the first position but your script will incorectly validate “QB235RB”

  2. sam8perry says:

    This is exactly what I was looking for and in such a simple package too! Thanks and much love.

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes