Created
October 6, 2012 06:49
-
-
Save jonathanconway/3844249 to your computer and use it in GitHub Desktop.
An ASP.NET MVC ValidationAttribute that ensures that an ABN (Australian Business Number) is both registered and Active.
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
public class AbnIsActiveAttribute : ValidationAttribute | |
{ | |
private static string AbnValidationUrl = "http://abr.business.gov.au/abrxmlsearch/AbrXmlSearch.asmx/ABRSearchByABN?searchString={0}&includeHistoricalDetails=N&authenticationGuid=74fd05cb-bbf6-4525-a68f-c553f6349222"; | |
private static string ShouldContainString = "<entityStatusCode>Active</entityStatusCode>"; | |
public AbnIsActiveAttribute() | |
{ | |
ErrorMessage = "This ABN is inactive or invalid."; | |
} | |
public override bool IsValid(object value) | |
{ | |
if (value == null) | |
return true; | |
var request = WebRequest.Create(string.Format(AbnValidationUrl, value.ToString().Replace(" ", ""))); | |
request.Timeout = 100000; | |
request.ContentType = "text/xml; charset=utf-8"; | |
request.Proxy = WebRequest.GetSystemWebProxy(); | |
request.Method = "GET"; | |
return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd().Contains(ShouldContainString); | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
ErrorMessage = string.Format(ErrorMessage, validationContext.DisplayName); | |
if (IsValid(value)) | |
return ValidationResult.Success; | |
else | |
return new ValidationResult(string.Format(ErrorMessage, validationContext.DisplayName)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment