UK Postcode Validation - JavaScript, VBScript, & PHP
These functions check the validity of a UK postcode specified by the supplied parameter. JavaScript, VBScript and PHP versions are available.
The definition of a valid postcode has been taken from the official specification, and from the list of BFPO codes. The functions also take into account which letters are valid in the various positions.
If the parameter is a valid postcode, the function returns it correctly formatted - i.e. in uppercase and with a space between the inward part and the output parts. Otherwise it returns a value of false.
In this example, the input field has an id of postcode, and the button has an onclick="testPostCode();" associated with it. This latter function calls the main checkPostCode function as follows:
function testPostCode () {
var myPostCode = document.getElementById('postcode').value;
if (checkPostCode (myPostCode)) {
document.getElementById('postcode').value = checkPostCode (myPostCode)
alert ("Postcode has a valid format")
}
else {alert ("Postcode has invalid format")};
Download compressed JavaScript, VBScript & PHP files (4,667 bytes)
Note: The routine was modified to include BFPO postcodes at the suggestion of C.R. Chafer whose contribution is gratefully acknowledged. At the same time, the rules for the letters permitted in the various parts of the postcode were implemented more stringently (8th March 2005). Support for Overseas Territories was added on 7th August 2005.