Created
April 13, 2012 09:00
-
-
Save legigor/2375231 to your computer and use it in GitHub Desktop.
GB Postcodes validation and formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.RegularExpressions; | |
namespace MyCommons | |
{ | |
public static class GBPostcodeUtil | |
{ | |
// Used regular expression from the article: http://www.qwghlm.co.uk/blog/?p=761 | |
// Original pattern: | |
public const string FORMATTED_MATCHPATTERN = "^[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]? {1}[0-9][ABD-HJLN-UW-Z]{2}$"; | |
// Modified for user flexibile input: | |
// 1. Lower case | |
// 2. Spaces | |
private const string PATTERN_BEGIN = "[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y0-9][A-HJKSTUWa-hjkstuw0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]?"; | |
private const string PATTERN_END = "[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}"; | |
public const string MATCHPATTERN = "^ *" + PATTERN_BEGIN + " *" + PATTERN_END + " *$"; | |
public static bool IsPostcodeValid(string postcode) | |
{ | |
return IsPostcodeValid(postcode.Trim().ToUpper().Replace(" ", ""), MATCHPATTERN); | |
} | |
private static bool IsPostcodeValid(string postcode, string pattern) | |
{ | |
try | |
{ | |
var match = Regex.Match(postcode, pattern); | |
return (match.Success && (match.Index == 0)) && (match.Length == postcode.Length); | |
} | |
catch | |
{ | |
// Something happened. We cant allow parse this postcode as we are not sure if it is valid. | |
return false; | |
} | |
} | |
public static string GetPostcodeWellFormatted(string postcode) | |
{ | |
if (!IsPostcodeValid(postcode)) | |
throw new FormatException("Invalid postcode: " + postcode); | |
postcode = postcode.Trim().ToUpper().Replace(" ", ""); | |
var endMatch = Regex.Match(postcode, PATTERN_END + "$"); | |
if (!endMatch.Success || endMatch.Groups.Count == 0) | |
throw new FormatException("Invalid postcode: " + postcode); | |
var endString = endMatch.Groups[0].Value; | |
postcode = postcode.Remove(postcode.Length - endString.Length); | |
postcode = String.Format("{0} {1}", postcode, endString); | |
if (!IsPostcodeValid(postcode, FORMATTED_MATCHPATTERN)) | |
throw new FormatException("Invalid postcode: " + postcode); | |
return postcode; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment