Looking for beta testers for WhizzyInvoice.com. Wanna help? Jump to: main content, navigation or the bottom.

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 (5)

What others have said about this post.

  • Amir said:

  • Stewart said:

  • techno-mole said:

  • Stewart said:

  • Simon said:

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

If you have trouble reading the code, click on the code itself to generate a new random code.

Going up? Back to the top