Last Updated: March 31, 2016
· jr-duboc

Regexp: how to validate a UK Postcode

In the UK, postcodes are a crucial part of someone's address, as they narrow addresses down to the street of the desired location (in countries like France, however, a postcode only tells you which city or town the address is located). It can be handy to make sure your users provide a valid UK postcode in a form. To do this, we'll need to match the postcode to a regexp... but what is a valid UK postcode, and what regexp can we use to make sure a postcode is indeed valid ? Wikipedia tells us UK postcodes can use the following formats ('A' stands for any letter, and '9' for any digit):

  • AA9A 9AA
  • A9A 9AA
  • A9 9AA
  • A99 9AA
  • AA9 9AA
  • AA99 9AA

To match any of these patterns, we can use the following regular expression: /^[a-zA-Z]{1,2}([0-9]{1,2}|[0-9][a-zA-Z])\s*[0-9][a-zA-Z]{2}$/ Let's decompose this so we know what it's doing:

  • We start by making sure our postcode isn't surrounded by anything else in our field, so we encase it between a beginning of input boundary (^) and an end of input boundary ($).
  • Then, we accept one or two letters [a-zA-Z]{1,2}
  • Followed by either one digit and a letter, or between one and two digits: ([0-9]{1,2}|[0-9][a-zA-Z])
  • An optional space \s*
  • Finally, a digit followed by two letters: [0-9][a-zA-Z]{2}

What have I missed? Is there a better way to write this? How hard is it to get UK addresses from a postcode using an external API? Let me know !