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))
-
function IsPostcode($postcode)
-
{
-
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))
-
return true;
-
else
-
return false;
-
}
How to use it? Just like a normal PHP function ….
Bibliography :
- http://php.net/preg_match – The preg_match function documentation + examples
- http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm – UK Government Data Standards Catalogue : Postcode
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”
This is exactly what I was looking for and in such a simple package too! Thanks and much love.