Skip to content

Instantly share code, notes, and snippets.

@feanz
Created December 2, 2013 16:38
Show Gist options
  • Save feanz/7752336 to your computer and use it in GitHub Desktop.
Save feanz/7752336 to your computer and use it in GitHub Desktop.
Postcode attribute
/// <summary>
/// Postcode validation attribute
/// Must be uppercase with a single optional space
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class PostcodeAttribute : DataTypeAttribute
{
private static readonly Regex _regex = new Regex(@"^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$");
//if you need lowercase and multi space use this one
//^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$
public PostcodeAttribute(): base(DataType.PostalCode)
{
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
var valueAsString = value as string;
return valueAsString != null && _regex.Match(valueAsString).Success;
}
public override string FormatErrorMessage(string name)
{
return string.Format("{0} is not a valid postcode", name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment