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
Download the check if a UK postcode is valid example.
Got something to say?
Join the discussion! You know how these things work; enter your details and comments below and be heard.
Comments 6