Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:46
Show Gist options
  • Save davybrion/3728776 to your computer and use it in GitHub Desktop.
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
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) };
}
}
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