UK Postcode Validation - JavaScript and PHP

These functions check the validity of a UK postcode specified by the supplied parameter. Both JavaScript 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.

Try the JavaScript routine: Enter Postcode:

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 newPostCode = checkPostCode  (document.getElementById('postcode').value);
  if (newPostCode) {
    document.getElementById('postcode').value = newPostCode;
    alert ("Postcode has a valid format")
  else alert ("Postcode has invalid format");

See here for the routines' change log. A test transaction is available here.

Download compressed JavaScript and PHP files (3.67 Kb)