0

I have a MVC4 project which must provide a high level of flexibility. Specifically, the client must be able to configure which fields are required when filling up a form. These settings are read from an XML file on each successful login. I use the values from the config file in a custom DataAnnotationsModelMetadataProvider to the ModelMetadata.IsRequired property accordingly. This works well.

Now I need to add localization. I wrote a custom localized RequiredAttribute and registered it in the Application_Start() method. This also works as expected, but obviously I must explicitly decorate a property with it.

My problem is that I need to use my custom attribute instead of the standard RequiredAttribute. When I dynamically set a property as required, the system uses the default one, which does not suit my needs.

The question is, how do I force the framework to use my custom attribute instead of the default one, when validating a Required property?

Andrei V
  • 7,306
  • 6
  • 44
  • 64
  • 1
    You can try in your MetadataProvider in CreateMetadata method replace all RequiredAttribute with your custom RequiredAttribute and then call base implementation passing new array of attributes. – Yevgeniy.Chernobrivets Nov 20 '13 at 09:07
  • Certainly seams like a solution. I will test it and get back. – Andrei V Nov 20 '13 at 10:00
  • @Yevgeniy.Chernobrivets, tried it. The attribute is correctly added to the attribute list. The problem I am facing now is that I can't seem to be able to configure the error message. All the changes I make are only reflected on the explicit attributes. – Andrei V Nov 21 '13 at 08:23
  • Did you try to provide ErrorMessage property for your custom requiredattribute when replacing standard? Maybe i do not fully understand what do you mean. – Yevgeniy.Chernobrivets Nov 21 '13 at 08:26
  • @Yevgeniy.Chernobrivets, maybe I'm not fully woken up yet. My apologies. I abandoned (for now) the idea of using custom attributes. I just insert a new `RequiredAttribute` when appropriate (gets successfully added). After that I just set the `ErrorMessage` property to my custom error message. Although I can see the message being "saved" in the newly added attribute, I does not get rendered in my view. I get the old, standard error message. The new message gets however correctly displayed for all the attributes that have been explicitly set in my ViewModel. – Andrei V Nov 21 '13 at 08:35
  • Maybe this thread will help you http://stackoverflow.com/questions/10766186/asp-net-mvc-3-0-model-localization-with-regularexpression-attribute – Yevgeniy.Chernobrivets Nov 21 '13 at 09:29

0 Answers0