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

前端 未结 2 1778
温柔的废话
温柔的废话 2021-02-15 12:23

When you decorate a model object\'s property with the Required attribute and don\'t specify ErrorMessage or ResourceType/Name you get the

相关标签:
2条回答
  • 2021-02-15 12:53

    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));
        }
    }
    
    0 讨论(0)
  • 2021-02-15 12:56

    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.

    0 讨论(0)
提交回复
热议问题