ASP.net MVC2 combines System.ComponentModel.DataAnnotations provides a very effective framework for entity validation. For handling error messages, it provides two choices by default:
String constants are read from an assembly resource file
But here we have our own resource file scheme, where we need to localize our control error messages. Because we can only supply constants in metadata, string manipulation is not possible. A more direct and cumbersome approach is to override all validation rules and localize string constants in validation rules.
[AttributeUsage (Attributetargets.parameter | Attributetargets.field | Attributetargets.property, AllowMultiple = False)]
public class CustomValidationAttribute:System.ComponentModel.DataAnnotations.ValidationAttribute
{
Public Customvalidationattribute (String message)
: Base (() => message. Localize ())
{
}
}
But doing so, on the one hand, will be more troublesome, all the validation rules we have to rewrite, on the other hand, we design model is particularly careful to use our own rewrite rules to achieve our goal, which will greatly reduce the development experience. To this end, today in particular again against the source of MVC2, I hope to find a usable extension point to solve this problem. Finally we find that we can achieve the desired effect by rewriting the Dataannotationsmodelvalidatorprovider Getvalidators method:
public class CustomDataAnnotationsModelValidatorProvider:System.Web.Mvc.DataAnnotationsModelValidatorProvider
{
protected override IEnumerable Getvalidators (Modelmetadata metadata, ControllerContext context, IEnumerable attributes )
{
foreach (Validationattribute attribute in attributes. OfType ())
{
if (!string. Isnullorwhitespace (attribute. errormessage))
{
Attribute. ErrorMessage = attribute. Errormessage.localize ();
}
}
var validators = base. Getvalidators (metadata, context, attributes);
return validators;
}
}
The code is very simple, we simply do a localized manipulation of the attribute's error message before calling the Getvalidators method. With this process, we can synchronize the localization of client authentication messages and server-side validation messages. The following job is to use this provider to replace its parent class, add the following code in Global.asax to complete:
ModelValidatorProviders.Providers.RemoveAt (0);
ModelValidatorProviders.Providers.Insert (0, New Customdataannotationsmodelvalidatorprovider ());
With such a small expansion, we can achieve our goal perfectly. However, for this small expansion, but it took us a lot of time.