Valid UK Postcode formats

May 20, 2008 12:24 by gareth

We are often required to validate input fields. One field that is often neglected or relies heavily on users inputting data in the correct format is the UK postcode field. The format of the postcode is listed here http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm.

We have a Regular Expression / Javascript solution that validates UK postcode formats. Briefly all valid formats are:

FormatExample
AN NAA M1 1AA
ANN NAA M60 1NW
AAN NAA CR2 6XH
AANN NAA DN55 1PT
ANA NAA W1A 1HQ
AANA NAA EC1A 1BB

 

The regex we use is:
/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/i

Or you could try this:
^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])
|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|
(GIR)\s?(0AA))$

 

Simple and effective.

UDPATE 2009 This will only validate UPPERCASE input. You will need to upper your input before validating it.

 


Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

August 28. 2008 13:50

It is not validating CV10 8QS post code

sunny

February 13. 2009 17:09

ı am from turkye and ı lıve here now

taha

June 19. 2009 14:40

its not validating a lot of UK codes

Pete Jackson

August 11. 2009 13:05

I use
(?:^|\W)[A-Za-z]{1,2}\d{1}[\d{1}|A-Za-z]?[  ]{1,2}\d{1}[A-Za-z]{1,2}(?Embarassed|\W|\z)

and if that fails attempt to build a partial match from the two groups returned from

(?:^|\W)([A-Za-z]{1,2}\d{1}[\d{1}|A-Za-z]?)[  ]{1,2}(\d{1}[A-Za-z]{1,2})(?Embarassed|\W|\z)?

ken

August 11. 2009 13:06

stupid smileys! that smiley is a colon and a $

ken

September 2. 2009 19:55

what is the vailed uk code for wooome?FrownSmile

Miley Ray Cyrus

September 2. 2009 19:55

(L)

Miley Ray Cyrus

October 3. 2009 07:35

It is not validating CV10 8QS post code

games

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 31. 2010 20:13

Calendar

July 2010
SuMoTuWeThFrSa
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567