我正在尝试继承RegularExpressionAttribute
以通过验证SSN来提高可重用性。
我有以下型号:
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; }
}
将在客户端和服务器上正确验证。我想将这个冗长的正则表达式封装到它自己的验证属性中,如下所示:
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";
}
}
然后我改变了我的FooModel
:
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; }
}
现在验证不会在客户端上呈现不显眼的数据属性。我不太确定为什么,因为看起来两者应该基本上是相同的。
有什么建议吗?
答案 0 :(得分:15)
在Application_Start
中添加以下行,将适配器与自定义属性相关联,该属性将负责发出客户端验证属性:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(SsnAttribute),
typeof(RegularExpressionAttributeAdapter)
);
您需要这个的原因是实现RegularExpressionAttribute
的方式。它没有实现IClientValidatable
接口,而是与RegularExpressionAttributeAdapter
相关联。
在您的情况下,您有一个派生自RegularExpressionAttribute
的自定义属性,但您的属性未实现IClientValidatable
接口,以便客户端验证工作,也没有与之关联的属性适配器(与其父类相反)。因此,您的SsnAttribute
应该实现IClientValidatable
接口,或者根据我的回答中的建议关联适配器。
据个人而言,我没有看到实现此自定义验证属性的重点。在这种情况下,常量可能就足够了:
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";
然后:
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; }
}
似乎很可读。