Validating UK postcodes with Javascript

2011-08-20

Postcodes in the UK do much more than mailsort. They are widely used to link individuals to various types of geographical, demographic and marketing data, and it's especially important that they are recorded and processed accurately. Thus, if your application processes UK postcodes, you'll need an effective way of validating them.

UK postcodes follow strict formatting rules. If you don't have access to the PAF, you can at least check that the postcodes in your application follow these rules. In this article, we offer a Javascript function that does just that.

This function is currently available with PHP, Javascript, Visual Foxpro. If you want to share this function in other languages, please contact us.

checkPostcode function

Remember, postcode validation function below only checks that the code is in the correct format. A code might pass this test but still not be a genuine postcode. To determine whether a postcode actually exists, you would need to access the Postcode Address File. (But even that wouldn't be a perfect check, as the PAF is never completely up to date, postcodes are constantly being added, and existing premises are occasionally re-coded. Also, Royal Mail acknowledges that the PAF contains errors.)

function checkPostCode (toCheck) {
  var alpha1 = "[abcdefghijklmnoprstuwyz]";
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";
  var alpha3 = "[abcdefghjkpmnrstuvwxy]";
  var alpha4 = "[abehmnprvwxy]"; 
  var alpha5 = "[abdefghjlnpqrstuwxyz]"; 

  var pcexp = new Array ();
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);
  var postCode = toCheck;
  var valid = false;
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
      pcexp[i].exec(postCode);
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      valid = true;
      break;
    }
  }
  if (valid) {return postCode;} else return false;
}

Download

Click to download above scripts (711 bytes).