Attempts to inherit RegularExpressionAttribute, no longer validates

I am trying to inherit RegularExpressionAttribute to improve reuse in SSN validation.

I have the following model:

 public class FooModel { [RegularExpression(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] public string Ssn { get; set; } } 

which will be correctly checked on the client and server. I wanted to encapsulate this long regular expression in my own validation attribute as follows:

 public class SsnAttribute : RegularExpressionAttribute { public SsnAttribute() : base(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$") { ErrorMessage = "SSN is invalid"; } } 

Then I changed my FooModel as follows:

 public class FooModel { [Ssn(ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] public string Ssn { get; set; } } 

Now the check does not display unobtrusive data attributes on the client. I'm not quite sure why, since it seems like they should be the same.

Any suggestions?

+6
source share
1 answer

In Application_Start add the following line to associate the adapter with your custom attribute, which will be responsible for issuing client-side validation attributes:

 DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof(SsnAttribute), typeof(RegularExpressionAttributeAdapter) ); 

The reason you need this is the RegularExpressionAttribute method. It does not implement the IClientValidatable interface, but rather has a RegularExpressionAttributeAdapter associated with it.

In your case, you have a custom attribute that comes from RegularExpressionAttribute , but your attribute does not implement the IClientValidatable interface to check the health of the client and does not have an attribute adapter associated with it (unlike its parent class). Thus, your SsnAttribute should either implement the IClientValidatable interface or bind the adapter, as suggested earlier in my answer.

This, as they say, personally, I don’t see much point in implementing this special verification attribute. In this case, the constant may be sufficient:

 public const string Ssn = @"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank"; 

and then:

 public class FooModel { [RegularExpression(Ssn, ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")] public string Ssn { get; set; } } 

seems quite readable.

+13
source

Source: https://habr.com/ru/post/953361/


All Articles