I am using ASP.NET MVC 3 and data annotations in my model and want to receive error messages from the database. Therefore, I wrote the 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 checks, for example:
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 two lines:
LocalizedRegularExpressionAttributeAdapter.SelfRegister(); LocalizedRequiredAttributeAdapter.SelfRegister();
I get an exception. Validation type names in unobtrusive client validation rules must be unique. The following type of validation has been examined more than once: required "when my model displays HTML for this property:
[LocalizedRequired(ErrorMessage = "global_Required_AccountName")] [LocalizedRegularExpression(User.ADAccountMask, ErrorMessage = "global_Regex_AccountName")] public string AccountName { get; set; }
What's wrong?
source share