4 Nov 2009

UK Postcode Validation using C# Regular Expression

Sigh - look up UK Postcode Validation and you'll get about a billion different RegEx patterns, all subtly different and wrong.

The following one works because I use the official UK Postcode rules as defined by the government here.
public static bool ValidateUkPostcode(string postcode)
{
return Regex.Match(postcode, "(^gir\\s?0aa$)|(^[a-z-[qvx]](\\d{1,2}|[a-hk-y]\\d{1,2}|\\d[a-hjks-uw]|[a-hk-y]\\d[abehmnprv-y])\\s?\\d[a-z-[cikmov]]{2}$)", RegexOptions.IgnoreCase).Success;
}
NOTE: This solution requires you to include the Regular Expressions namespace at the top of your code:
using System.Text.RegularExpressions;
PS. Wondering why the regex allows "GIR 0AA"? For some reason Girobank were allowed their own non-conformant postcode. There's also "SAN TA1" for kids xmas posts, but that's just silly!!

5 comments:

  1. Anonymous5:26 pm

    Dude, do these support all those weird new london postcodes which have an extra character in the middle

    ReplyDelete
  2. Anonymous10:06 am

    Thanks
    It's Working

    ReplyDelete
  3. Acording to http://www.doogal.co.uk/files/postcodes.zip, there are 556 codes that doesn't match your regular expression.

    ReplyDelete
    Replies
    1. Thanks for the heads-up. Before I go to the trouble of setting up a test rig, can you give me an example of a code that fails the regex?

      Delete
  4. Great work, saved me a load of time (regex scares me, was gonna do it the old fashioned way).

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!