asp.net-mvc – 尝试继承RegularExpressionAttribute,不再验证
|
我正在尝试继承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; }
}
现在,验证不会在客户端上呈现不显眼的数据属性.我不太清楚为什么,因为这看起来两者本质上应该是一回事. 有什么建议? 解决方法在Application_Start中添加以下行以将Adaptiveater与您的自定义属性相关联,该属性将负责发出客户端验证属性: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; }
}
看起来很可读. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – Visual Studio 2012:无法附加进程.已
- asp.net – 将通用模型的子类传递给剃刀视图
- 如何调试asp.net mvc 4源代码?
- 我应该如何组织我的ASP.Net主题和常见的CSS文件
- asp.net – 考虑Scalablity和友好URL的GUID替代方
- asp.net – Session_End不启动?
- asp.net-mvc – WebApi Action过滤器调用两次
- asp.net-mvc-3 – WSFederationAuthenticationMo
- asp.net – [DataType(DataType.EmailAddress)]和
- asp.net-mvc-3 – ASP.Net MVC 3剃刀:部分定义但
