I'm trying to inherit the RegularExpressionAttribute
to improve reusability with validating SSNs.
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 validate correctly on the client and server. I wanted to encapsulate that lengthy regular expression into its own validation attribute like so:
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
like so:
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 validation doesn't render the unobtrusive data attributes on the client. I'm not quite sure as to why, since this seems like the two should essentially be the same thing.
Any suggestions?
IClientValidatable
. The reason I wanted an attribute for this instead of using aRegularExpressionAttribute
was mainly because I didn't want to figure out where to put apublic const string
regex in my project (there are only two hard things in Computer Science...), but also because there seemed to be an emergin pattern from the MVC guys to create attributes that are basically no more than aRegularExpressionAttribute
(PhoneAttribute',
EmailAddressAttribute`, etc), so I felt justified – Footboy