0

I'm really lost trying to create custom generic validation messages for my MVC3 application.

I read many tutorials and the biggest part of them suggest one of these options:

  1. Create an App_GlobalResources folder and inside that put my custom resource, them I change global.asax, passing the string name of my resource to DefaultModelBinder.ResourceClassKey property. Change the resource's build action to "Embeded Resource".

  2. Right click the project, then go properties, click "Resources" tab and create your custom resource. Set it's access modifier to "Public".

The first one didn't work to me, I have the following keys in my resource: DefaultModelBinder_ValueRequired, InvalidPropertyValue, PropertyValueInvalid, PropertyValueRequired and none of them was used when my I tried to submit and form with empty value in a required attribute of my model. I've put this code at global.asax Application_Start method:

DefaultModelBinder.ResourceClassKey = "My_Resource_Name";

With the second method, I've created an resource with the same keys as the first one. None of them was used by default when a property is invalid or empty (I've changed the ResourceClassKey in global.asax too, but without success). But when I added some parameters to data annotation in my model:

[Required(ErrorMessageResourceType = typeof(MyResourceFile), ErrorMessageResourceName = "MyCustomKey")]

When the attribute of that data annotation is empty, my message defined with "MyCustomKey" is used!

But I really don't want to manually set this to all my attributes, I want to replace the default error messages like: "The {0} field is required."

IPValverde
  • 2,019
  • 2
  • 21
  • 38

1 Answers1

0

That message is part of DataAnnotations. The default message is compiled into the DataAnnotations assembly in the resource file under System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources and is RequiredAttribute_ValidationError=The {0} field is required. You can try to download the source, change that part and rebuild it.

There doesn't seem to be a simple global way of changing it. You could try this, otherwise it looks like you are stuck with adding your attribute to every field. Or use something like this:

public class SomeModel
{
    [Required(ErrorMessage = "The article is required")]
    public string Article { get; set; }

    [StringLength(512, ErrorMessage = "Must be less than 512 characters.")]
    public string URL { get; set; }
}
Community
  • 1
  • 1
Garrett Fogerlie
  • 4,450
  • 3
  • 37
  • 56