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

问题描述 投票:20回答:2

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

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

我能做些什么来让客户端验证工作?

代码示例:

public sealed class MailAddressAttribute : RegularExpressionAttribute
{
    public MailAddressAttribute()
        : base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
    {
    }
}
asp.net regex asp.net-mvc data-annotations client-side-validation
2个回答
29
投票

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

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

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


9
投票

延伸正确的答案

public class EmailAttribute : RegularExpressionAttribute
{
    static EmailAttribute()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
    }

    public EmailAttribute()
        : base(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$") //^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$
    {

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.