Created
September 15, 2012 16:46
-
-
Save davybrion/3728776 to your computer and use it in GitHub Desktop.
code snippets for "Customizing ASP.NET MVC’s Required Property Validation Messages" post
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 ConventionsBasedRequiredAttributeAdapter : RequiredAttributeAdapter | |
{ | |
public ConventionsBasedRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) | |
: base(metadata, context, attribute) {} | |
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() | |
{ | |
string errorMessage; | |
var className = Metadata.ContainerType.Name; | |
var propertyName = Metadata.PropertyName; | |
var specificKey = string.Format("{0}_{1}_required", className, propertyName); | |
// TODO: make the ResourceManager configurable | |
errorMessage = Resources.ResourceManager.GetObject(specificKey) as string; | |
if (string.IsNullOrEmpty(errorMessage)) | |
{ | |
var genericMessageWithPlaceHolder = (string)Resources.ResourceManager.GetObject("Generic_required_field_message"); | |
if (!string.IsNullOrEmpty(genericMessageWithPlaceHolder)) | |
{ | |
errorMessage = string.Format(genericMessageWithPlaceHolder, Metadata.DisplayName); | |
} | |
} | |
if (string.IsNullOrEmpty(errorMessage)) | |
{ | |
errorMessage = ErrorMessage; // fallback to what ASP.NET MVC would normally display | |
} | |
return new[] { new ModelClientValidationRequiredRule(errorMessage) }; | |
} | |
} |
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
DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(RequiredAttribute), | |
(metadata, controllerContext, attribute) => new ConventionsBasedRequiredAttributeAdapter(metadata, | |
controllerContext, (RequiredAttribute)attribute)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment