Sisira 95

UK ZIP Code validation ?

I have tried

^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$



These are fails in some conditions. How can i get the right regex for validating the UK ZIP code.

1 answer

Ktash 1851

Questions like this often times do better on SO. That said, there was an SO question on this topic (link) which lead to an XML Schema Definition page which in turn gives the following:

(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})

Source. Might want to tweak it for case-insensitive, but that should at least set you on the right track.

Answered almost 8 years ago by Ktash
  • Probably simpler just to uppercase the post code before putting it through the regex: Rob Crowther almost 8 years ago
  • Yes, as long as that's easy, it's a good way to solve the problem. Though if he's not working in JS it will depend on the language. Sometimes it's just as easy to add an i at the end to make it insensitive. Ktash almost 8 years ago