How to change validation error messages in MVC

2019-07-10 15:02发布

问题:

Hi I've been trying to change the validation error messages (in MVC3) and read a lot of threads and find out from this thread:

  • Create App_GlobalResources folder for your project (right click to
    project -> Add -> Add ASP.NET folder -> App_GlobalResources).
  • Add a resx file in that folder. Say MyNewResource.resx.
  • Add resource key PropertyValueInvalid with the desired message format (e.g. "content {0} is invalid for field {1}"). If you want to change PropertyValueRequired too add it as well.
  • Add the code DefaultModelBinder.ResourceClassKey = "MyNewResource" to your Global.asax startup code.

But I cannot make it work. Here is a clean MVC 3 web application I want to change the validation messages. Please make it work for me as and as a sample for everybody else.

here is the link for my test project

回答1:

After some searching and trial and error, I used some code based on this blog post. Adapted code below.

Add a new class to your project:

using System.Web.Mvc;
public class FixedRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public FixedRequiredAttributeAdapter (ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    { 
        // set the error message here or use a resource file
        // access the original message with "ErrorMessage"
        var errorMessage = "Required field!":
        return new[] { new ModelClientValidationRequiredRule(errorMessage) };
    }
}

Tell MVC to use this adapter by changing app start in global_asax:

    protected void Application_Start()
    {
        ...
        DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
            typeof(RequiredAttribute),
            (metadata, controllerContext, attribute) => new FixedRequiredAttributeAdapter(
                metadata,
                controllerContext,
                (RequiredAttribute)attribute));

There's more you could do with the error message such as getting from a resource file based on the class/property:

    var className = Metadata.ContainerType.Name;
    var propertyName = Metadata.PropertyName;
    var key = string.Format("{0}_{1}_required", className, propertyName);

Tested with MVC5.


Update: Looks like this only works for javascript/unobtrusive validation. If you turn off javascript to get post-back validation, it still shows the "The {} field is required".