Javascript UK Postal Code Checker

Possible duplicate:
UK Postal Code Extension (Comprehensive)

I have the following code for checking zip codes in javascript:

function valid_postcode(postcode) { postcode = postcode.replace(/\s/g, ""); var regex = /[AZ]{1,2}[0-9]{1,2} ?[0-9][AZ]{2}/i; return regex.test(postcode); } 

Tests:

 CF47 0HW - Passes - Correct CF47 OHW - Passes - Incorrect 

I have done a lot of research, but cannot find a final regular expression for this general validation requirement. Can someone point me in the right direction?

+4
source share
3 answers

Make your regex more stringent by adding ^ and $. This should work:

 function valid_postcode(postcode) { postcode = postcode.replace(/\s/g, ""); var regex = /^[AZ]{1,2}[0-9]{1,2} ?[0-9][AZ]{2}$/i; return regex.test(postcode); } 
+6
source

You want a "final regex" - given all the permutations of the UK zip codes, this should therefore be "too big." Here is the one I used in the past

 "(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})" 

Please note: I never use AZ, for example, because in each part certain letters are always excluded.

+4
source

The problem is the first line of your function. By cutting spaces from the target line, you allow false positives.

Will CF47OHW match [AZ] {1,2} [0-9] {1,2}? [0-9] [AZ] {2}

 CF matches [AZ] 4 matches [0-9]{1,2} (blank) matches \s? 7 matches [0-9] OH matches [AZ]{2} W gets discarded 

So, as Halfgrave said, adding the start and end characters (^ and $) will fix it.

At this point, can you also remove \ s? a bit from the middle of your regular expression.

But! Despite fixing the error, your regular expression will still not work the way you would like. You should look at the following pretty good answer on this Regex (comprehensive) site in the UK

+1
source

All Articles