Javascript UK postcode regex

Phil Young picture Phil Young · Jun 18, 2012 · Viewed 10.8k times · Source

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.

Answer

Qtax picture Qtax · Jun 18, 2012

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