MGBlog
Thursday, 30 March 2006
Thu, 30 Mar 2006 - 09:58pm (GMT+1)
The following regular expression can be used to validate UK postcodes. I'm posting this here as I can never find it when I need it.
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
It is not case sensitive. It matches postcodes starting GIR which are for GiroBank which may not be required.
Comments
Re: Postcode Regular Expression
To change the expression to allow postcodes with no space in the middle you need to put {0,1} after the space giving you this:
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$
Re: Postcode Regular Expression
You might be interested in this:
[a-zA-Z]{1,2}[0-9][0-9A-Za-z]? [0-9][a-zA-Z]{2}
and you should be okay for:
"A9 9AA", "A99 9AA", "AA9 9AA", "AA99 9AA", "A9A 9AA" or "AA9A 9AA",
see:
http://en.wikipedia.org/wiki/UK_postcodes
Re: Postcode Regular Expression
Alex you are the genius. Keep It Simple Stupid (KISS).
Used it on my project actually!
This first one works but very, very long.
ALL THE SAME THANKS GUYS.
Add Your Comment