I have the following validation/presentation that I use on a postal code field, in a ViewModel, in my ASP.NET MVC web site. I'd like to share this implementation with 5 other postal code editors, on other models, in my application. How can I avoid duplicating this code?
[Required]
[RegularExpression(LocationMatch.NorthAmericanPostalCodePattern,
ErrorMessage = "You may look up cities here, but must submit a North American postal code")]
[Display(Name = "Postal Code", Prompt = "or type city")]
[Remote("ValidatePostalCode", "Utilities")]
[CustomValidation(typeof(CandidateMobileEditor), "ValidatePostalCode")]
public string PostalCode { get; set; }
public static ValidationResult ValidatePostalCode(string postalCode) {
return LocationMatch.Closest(postalCode) == null ?
new ValidationResult("Postal code not found") : null;
}
public void Load(Candidate sourceProfile) {
PrimaryPostalCode = sourceProfile.Account.FormattedPostalCode;
}
public void Save(Candidate targetProfile) {
targetProfile.Account.FormattedPostalCode = LocationMatch.Closest(PrimaryPostalCode).PostalCode;
}
Additionally, I have the following JavaScript associated with each postal code field. I mention this for completeness, as I am aware of some ways to trigger this to be activated from common code, but only if I can cause a common template to load or decorate the model with some common custom attributes.
singletons.lac = new locationAutocomplete("input[name='PrimaryPostalCode']");
function locationAutocomplete(selector) {
var cache = {}, lastXhr;
var locationField = $(selector);
locationField.autocomplete({
minLength: 5,
delay: 0, // note the lookup delay is increased during the first search event
search: function (event, ui) { locationField.autocomplete("option", "delay", 300); },
change: function (event, ui) { locationField.change(); },
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON(SiteContext.VirtualRoot + "Utilities/GetMatchingLocations", request, function (data, status, xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
}