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,985 bytes)
Note: These routines were last modified on 7th October 2009 after Jan de Groot had brought to the author's attention that the Post Office were now allowing the additional characters 'PMNRVXY' in the third position of the Outward code (despite the fact that the official specification had not changed!).