I use ASP.NET MVC 3 and Data Annotations in my model, and want to retrieve the Error Messages from a database. So I wrote inherited attributes:
public class LocalizedRequiredAttribute : RequiredAttribute
{
public LocalizedRequiredAttribute(){}
public override string FormatErrorMessage(string name)
{
return GetByKeyHelper.GetByKey(this.ErrorMessage);
}
}
public class LocalizedRegularExpressionAttribute : RegularExpressionAttribute
{
public LocalizedRegularExpressionAttribute(string pattern) : base(pattern){}
public override string FormatErrorMessage(string name)
{
return GetByKeyHelper.GetByKey(this.ErrorMessage);
}
}
I wrote 2 "adapters" for these attributes to enable client validations, such as this:
public class LocalizedRequiredAttributeAdapter : DataAnnotationsModelValidator<LocalizedRequiredAttribute>
{
public LocalizedRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, LocalizedRequiredAttribute attribute)
: base(metadata, context, attribute)
{
}
public static void SelfRegister()
{
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };
}
}
And in my global.asax I have these 2 lines:
LocalizedRegularExpressionAttributeAdapter.SelfRegister();
LocalizedRequiredAttributeAdapter.SelfRegister();
I get an exception "Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required" when my model renders the HTML for this property:
[LocalizedRequired(ErrorMessage = "global_Required_AccountName")]
[LocalizedRegularExpression(User.ADAccountMask, ErrorMessage = "global_Regex_AccountName")]
public string AccountName { get; set; }
What is wrong?