Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 874
ansar hussain Avatar asked Aug 02 '26 04:08

ansar hussain


1 Answers

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.

like image 81
John McCollum Avatar answered Aug 03 '26 17:08

John McCollum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!