Search code examples
javascriptregexpostal-code

Javascript UK postcode regex


I have a javascript regex which validates UK postcodes. It works well, but it doesn't take into account that some people write it with spaces in the middle and others don't. I've tried to add this but cant work it out :S UK postcodes are mainly 2 letters followed by 1 or 2 numbers, optional whitespace & 1 number and 2 letters.

Here is my regex which validates postcodes without spaces:

[A-PR-UWYZa-pr-uwyz0-9][A-HK-Ya-hk-y0-9][AEHMNPRTVXYaehmnprtvxy0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]?{1,2}[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}|(GIRgir){3} 0(Aa){2})$/g

Any ideas?

Edit

I changed the regex as I realised one group was missing lowercase chars.


Solution

  • An alternative solution would be to remove all spaces from the string, then run it through the regular expression that you already have:

    var postalCode = '…';
    postalCode = postalCode.replace(/\s/g, ''); // remove all whitespace
    yourRegex.test(postalCode); // `true` or `false`