使用继承的 RegularExpressionAttribute 进行 ASP.NET MVC 数据注释客户端验证

标签 asp.net regex asp.net-mvc data-annotations client-side-validation

为了保持我的模型验证干净,我想实现我自己的验证属性,比如 PhoneNumberAttributeEmailAttribute .其中一些可以有利地实现为从RegularExpressionAttribute 继承的简单类。 .

但是,我注意到这样做会破坏这些属性的客户端验证。我假设某种类型的绑定(bind)在某处失败。

有什么想法可以使客户端验证正常工作吗?

代码示例 :

public sealed class MailAddressAttribute : RegularExpressionAttribute
{
    public MailAddressAttribute()
        : base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
    {
    }
}

最佳答案

您需要为您的自定义属性注册一个客户端验证适配器。在这种情况下,您可以使用 System.Web.Mvc 中现有的 RegularExpressionAttributeAdapter,因为它应该与标准正则表达式属性完全相同。然后在您的应用程序开始使用时注册它:

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

如果您编写需要自定义客户端验证的属性,您可以通过继承 DataAnnotationsModelValidator 来实现自己的适配器。 (另见 Phil Haack's blog)。

关于使用继承的 RegularExpressionAttribute 进行 ASP.NET MVC 数据注释客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627843/

相关文章:

c# - 在 ApiController 中添加自定义响应 header

c# - asp.net core web.api 应用程序无法启动

regex - 使用 sed 修改 tomcat server.xml 配置

javascript - 如何在 html 表体中使用 jQuery 或 javascript?

jquery - jQuery 自动完成的服务器端缓存策略?

jquery - 页面加载时 - Knockout/Javascript 有 1-4 秒的延迟

c# - ASP.NET Core 2 - ReSharper "Create Razor View"将新 View 添加到 Pages 文件夹

c# - 从 web.config 读取 AuthorizationSection 提供了不正确的值

java - 在 Java 中构造正则表达式

.net - 你如何获得正则表达式的组名?