MVC3: How to change the generic [Required] validation message text?

北慕城南 提交于 2019-12-12 07:57:31

问题


When you decorate a model object's property with the Required attribute and don't specify ErrorMessage or ResourceType/Name you get the validation message in the interpolated form of "The {0} field is required.", where param 0 is the value of the DisplayName attribute of that property.

I want to change that default string to something else but I want to keep the generic nature of it, that is I don't want to specify ErrorMessage or ResourceType/Name for every property of the model object. Where is the default string stored and how can I change it?


回答1:


Deriving your own attribute is a fair option and probably has the lowest overhead to get started, but you'll need to go back and change all your existing uses of [Required]. You (and any others on your team) will also need to remember to use (and teach newcomers to use) the right one going forward.

An alternative is to replace the ModelMetadataProviders and ModelValidatorProviders to return strings from a resource file. This avoids the drawbacks above. It also lays the groundwork for replacing messages for other attributes (e.g., MaxLengthAttribute) and for supporting additional languages.

protected void Application_Start()
{
    var stringProvider = new ResourceStringProvider(Resources.LocalizedStrings.ResourceManager);
    ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(stringProvider);
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider(stringProvider));
}

Here is the full source, documentation, and a blog post describing the usage.




回答2:


Have you tried creating a derived class of RequiredAttribute and overriding the FormatErrorMessage method? This should work:

public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(string.Format("This is my error for {0}", name));
    }
}


来源:https://stackoverflow.com/questions/10317259/mvc3-how-to-change-the-generic-required-validation-message-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!