Javascript: check if a UK postcode is valid
- May 12th, 2007
- Posted by Stewart
- Permalink
- 5 Comment(s)
![]()
Here’s two useful postcode functions; one that will help for checking if a string is in the valid format for a UK postcode; and another that formats a string into a nice postcode format. They both use regular expressions to make them fast! You could use them for client-side form validation.
http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm
/* 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);
}
/* 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
5 Responses to “Javascript: check if a UK postcode is valid”
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.
Hi Amir, you could change the regular expression to allow characters as well as numbers:
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
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.
To cater for the newer central london postcodes, the regex string used should be:
var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}/i;
Leave Feedback