Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 607
Phil Young Avatar asked Dec 01 '22 22:12

Phil Young


2 Answers

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`
like image 129
Mathias Bynens Avatar answered Dec 04 '22 12:12

Mathias Bynens


2 letters followed by 1 or 2 numbers, optional whitespace & 1 number and 2 letters.

Example:

/^[a-z]{2}\d{1,2}\s*\d[a-z]{2}$/i

Explained with http://www.myregextester.com/

  ^                        the beginning of the string
----------------------------------------------------------------------
  [a-z]{2}                 any character of: 'a' to 'z' (2 times)
----------------------------------------------------------------------
  \d{1,2}                  digits (0-9) (between 1 and 2 times
                           (matching the most amount possible))
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  \d                       digits (0-9)
----------------------------------------------------------------------
  [a-z]{2}                 any character of: 'a' to 'z' (2 times)
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
like image 42
Qtax Avatar answered Dec 04 '22 12:12

Qtax