ansar hussain
ansar hussain

Reputation: 31

Validating UK Post Codes using regular expressions

I want to validate a field with a UK Post Code. What regular expression could be used to validate this field?. (([A-Z]{1,2}[0-9][0-9A-Z]{0,1})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$ does appear valid because it has the exception GIR 0AA.

So, please help me to write an expression without any exception

Upvotes: 3

Views: 2641

Answers (3)

Rob
Rob

Reputation: 45771

Side note: GIR 0AA is listed as an exception in your regular expression because it is a valid UK post code for what are esentially historical reasons (search for it in the Wikipedia article, it's given special mention).

There is no trivial regular expression you can write to validate a UK post code as there's no surety that, for example, GU78 2AB is valid (the GU78 outward area may only contain 2AA, but not 2AB), whereas GU77 2AB may well be considered valid.

You can use a regular expression to validate the form and structure of a piece of text to determine if it matches the requirements to be considered a post code. I believe that, broadly speaking, the following regular expression will satisfy that:

(([A-Z]{1,2}[0-9]{1,2})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$

Upvotes: 1

John McCollum
John McCollum

Reputation: 5142

If you do mean post code, wikipedia has a section on validation. One regex that it recommends is:

((A[BL]|B[ABDHLNRST]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|([E|N|NW|SE|SW|W]1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|[SW|W]([1-9][0-9]|[2-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2}

The advantage of this one is that it catches some invalid areas and districts.

Upvotes: 3

Sachin R
Sachin R

Reputation: 11876

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

Upvotes: 0

Related Questions