使用继承的 RegularExpressionAttribute 进行 ASP.NET MVC 数据注释客户端验证
为了保持模型验证干净,我想实现自己的验证属性,例如 PhoneNumberAttribute
和 EmailAttribute
。其中一些可以有利地实现为从 RegularExpressionAttribute
继承的简单类。
但是,我注意到这样做会破坏这些属性的客户端验证。我假设某种类型绑定在某处失败。
有什么想法可以让客户端验证正常工作吗?
代码示例:
public sealed class MailAddressAttribute : RegularExpressionAttribute
{
public MailAddressAttribute()
: base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
{
}
}
To keep my model validation clean I would like to implement my own validation attributes, like PhoneNumberAttribute
and EmailAttribute
. Some of these can favorably be be implemented as simple classes that inherit from RegularExpressionAttribute
.
However, I noticed that doing this breaks client side validation of these attributes. I am assuming that there is some kind of type binding that fails somewhere.
Any ideas what I can do to get client side validation working?
Code example:
public sealed class MailAddressAttribute : RegularExpressionAttribute
{
public MailAddressAttribute()
: base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要为自定义属性注册客户端验证适配器。在这种情况下,您可以使用 System.Web.Mvc 中现有的 RegularExpressionAttributeAdapter,因为它的工作方式应该与标准正则表达式属性完全相同。然后在您的应用程序开始使用时注册它:
如果您编写一个需要自定义客户端验证的属性,您可以通过继承 DataAnnotationsModelValidator (另请参阅 菲尔·哈克的博客)。
You'll need to register a client-side validation adapter for your custom attribute. In this case you can use the existing RegularExpressionAttributeAdapter in System.Web.Mvc, since it should work exactly the same as the standard regex attribute. Then register it when your application start using:
Should you write an attribute that requires custom client-side validation, you can implement your own adapter by inheriting from DataAnnotationsModelValidator (see also Phil Haack's blog).
正确答案的延伸
extending of the right answer