Skip to content

Instantly share code, notes, and snippets.

@mat-mcloughlin
Last active July 30, 2016 21:48
Show Gist options
  • Save mat-mcloughlin/ad2ac503d1baa7fd0599 to your computer and use it in GitHub Desktop.
Save mat-mcloughlin/ad2ac503d1baa7fd0599 to your computer and use it in GitHub Desktop.
Value Object
public class Postcode
{
private readonly string value;
public Postcode(string value)
{
if (CheckPostcodeIsValid(value))
{
throw new InvalidPostcodeException();
}
this.value = value;
}
public static bool TryParse(string candidate, out Postcode postcode)
{
postcode = null;
if (CheckPostcodeIsValid(candidate))
{
return false;
}
postcode = new Postcode(candidate.Trim().ToUpper());
return true;
}
public static implicit operator string (Postcode postcode)
{
return postcode.value;
}
public override string ToString()
{
return this.value;
}
public override bool Equals(object obj)
{
var other = obj as Postcode;
if (other == null)
{
return base.Equals(obj);
}
return object.Equals(this.value, other.value);
}
public override int GetHashCode()
{
return this.value.GetHashCode();
}
private static bool CheckPostcodeIsValid(string value)
{
var regex = new Regex(@"(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-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})");
var match = regex.Match(value);
return match.Success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment