This project is read-only.

Custom Localized validation error messages

Aug 27, 2009 at 10:49 PM


In our project we need to display localized validation messages to the user. We are not setting the current thread culture based on the user's browser preferences due to our design designs made in our application. I see the DataAnnotations in both 3.5sp1 and in 4.0 (current version) versions do not support specifying a custom provider for Error message resource provider.  Hence I believe xVal also don't support this. For server side validation, we extended the DataAnnotationsModelBinder class and injected our localization provider and changing the error messages in OnPropertyValidating method.

However for a GET operation as the evaluation doesn't happen when rendering the content and xVal grabs the error message specified on the validation attributes, I am injecting our localized validation messages after xVal gets the error messages using Reflection. Here is the code snippet.

 public static ValidationInfo PerformClientSideValidation<T>(this HtmlHelper html, string elementPrefix)
            // Commented out  ---   var controller = some code; 

           //Commented out    ---   var repository = localized repository;

            var vinfo =  html.ClientSideValidation<T>(elementPrefix);

            // loop through the rules in the result and replace errormessages with the right language.
            var fieldInfo = vinfo.GetType().GetField("rules",
                                                  BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic);
            var ruleset = (RuleSet) fieldInfo.GetValue(vinfo);
            foreach (var key in ruleset.Keys)
                var rules = ruleset[key];
                foreach (var rule in rules)
                    if (!string.IsNullOrEmpty(rule.ErrorMessage))
                        rule.ErrorMessage = repository.GetString(rule.ErrorMessage, controller.Language);

            return vinfo;

I tried the approach of extending the DataAnnotationsRulesProvider class in xVal and replacing the DataAnnotationsRulesProvider with my provider but as the Providers property in ActiveRuleProviders is a static property and I need to set the culture in my provider based on each user's request, I would need to lock the Providers property before changing the collection.

It would be great if there is an easy means to specify our own providers to get the localization messages. Is this something that will be supported in near future? Are there any suggestions or better approaches to solving this problem? Please let me know.