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!!
If I helped you out today, you can buy me a beer below. Cheers!