Question

I'm using the following javascript to check if a UK postcode is valid

var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i; 
if(postcodeRegEx.test($("#postcode").val())) { ... }

This works fine for mostly every postcode I've fired at it but for some reason WC2F 3BT doesn't return true.

Can anyone who understands regexbetter explain what the problem is and how I can fix it?

Was it helpful?

Solution 2

If you want to understand what a specific regular expression is looking for there are lots of helpful online tools that will do this for you, my personal preference is http://regex101.com

The specific problem with your regular expression is that it assumes all postcodes are composed of one/two letters followed by one/two numbers and then a single number followed by two letters.

However this is not the case, as detailed in the wikipedia articles for UK Postcodes:

The 'outward' part identifies first the postcode area, using one or two letters (for example L for Liverpool, RH Redhill and EH Edinburgh). A postal area may cover a wide area, for example RH covers north Sussex, which has little to do with Redhill historically apart from the railway links, and Belfast (BT) covers the whole of Northern Ireland. These letter(s) are followed by one or two digits (and sometimes a final letter) to identify the appropriate postcode district (for example W1A, RH1, RH10 or SE1P)

Where the 'outward' part means the first half of the post code.

Therefore in order to cover all valid UK post codes you need to add an optional letter component as already detailed in other answers you've received, reproducing @Martyn's suggestion for completeness of this answer:

/[A-Z]{1,2}[0-9]{1,2}[A-Z]?\s?[0-9][A-Z]{2}/i

OTHER TIPS

According to HTML5Pattern.com, a UK post code is:

[A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]? [0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}
/[A-Z]{1,2}[0-9]{1,2}[A-Z]?\s?[0-9][A-Z]{2}/i

You missed an optional letter, thats why it diddnt work. Your original regex was looking for one to two letters. Followed by two numbers possibly separated by a space.

/[A-Z]{2}\d[A-Z]?\s?\d[A-Z]{2}/i

This should match:

WC1E 7BT
CW3 9SS
SE5 0EG
SE50EG
se5 0eg

Remember, though, that some UK postcodes have only one letter in the first part (e.g. N1 7TE). So [A-Z]{2} would need to be [A-Z]{1,2}.

This one is comprehensive, covering London central postcodes as well as the standard X[X]n[n] nXX postcodes. (From Expresso Regex tool library).

\b([A-Z]{1,2}\d[A-Z]|[A-Z]{1,2}\d{1,2})\ +\d[A-Z-[CIKMOV]]{2}\b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top