UK postcode format
UK postcodes have a particular format of numbers and letters. You can check out the format on the government website which documents this in detail:-
http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards/address/postcode.aspx
Checking a postcode is valid
This function tests to see if the value is in the correct format for a UK postcode.
/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return postcodeRegEx.test(p);
}
Format a valid postcode
You can also use this function to format a postcode into a nice to read format:-
/* formats a VALID postcode nicely: AB120XY -> AB1 0XY */
function formatPostcode(p) {
if (isValidPostcode(p)) {
var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
return p.replace(postcodeRegEx,"$1 $2");
} else {
return p;
}
}
Download the check if a UK postcode is valid example.

Comments (6)
What others have said about this blog post.
12 May 2008 Amir said:
Hi, This has proven to be really useful to me. Any suggestions on how to make the function "isValidPostcode" valid for the post code "GIR 0AA". Obviously I can do an if/else statement, but I would be interested to see what you would do.
12 May 2008 Stewart said:
Hi Amir, you could change the regular expression to allow characters as well as numbers:
25 Jul 2008 techno-mole said:
i wonder if you could help with something, basically i am wondering if the code could be adapted to not only check for a valid post code, but also check for a specific set of post codes, and display an alert. so for example if you entered you post code into a form on a website, this script could be used by calling the function when a button is clicked, but could it also then throw out an alert saying what ever if it finds a particular post code, or the first part of a post code ? and how could that be done ? cheers
28 Jul 2008 Stewart said:
Yes that is possible. It would probably be best to use this function along with some other javascript to achieve this. Contact me with an example of what you want to do and I'll see if I can help.
18 Aug 2008 Simon said:
To cater for the newer central london postcodes, the regex string used should be:
13 Jul 2011 Mike Y said:
It works better if you do a complete string match by specifying start and end markers '^' and '$' respectively: var postcodeRegEx = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;