27

I'm building a MVC web application with C#. Since the site will be multilingual, I've implemented my own ResourceManager. This class is responsible for fetching the required resource strings from a database/cache depending on the currents thread culture and works fine so far.

My problem is, I'd like to use the my custom ResourceManager solution to fetch validation error messages when for example using the Required Attribute on a property. Can this be done?

Mats
  • 14,902
  • 33
  • 78
  • 110

1 Answers1

53

The RequiredAttribute allows to use a custom resource manager:

[Required(
    ErrorMessageResourceType = typeof(CustomResourceManager), 
    ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }

UPDATE:

Another possibility is to write your custom attribute:

public class CustomRequiredAttribute : RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return YourCustomResourceManager.GetResource(name);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    My ResourceManager is really a custom solution and is neither hooked up into MVC in any way nor does it implement any interfaces except the one I created. What changes are required so that my ResourceHandler can be used in this manner? – Mats Feb 27 '10 at 15:49
  • Is anything else required to make custom attributes work? I've tried this and it doesn't seem to work. Do I need to create my own EditorFor extension method to make use of the new attribute type? – Matthew Dresser Oct 26 '13 at 03:33