为了保持模型验证的清洁,我想实现自己的验证属性,例如PhoneNumberAttribute
和EmailAttribute
。其中一些可以有利地实现为从RegularExpressionAttribute
继承的简单类。
但是,我注意到这样做会破坏这些属性的客户端验证。我假设某种类型的绑定在某处失败。
我能做些什么来让客户端验证工作?
代码示例:
public sealed class MailAddressAttribute : RegularExpressionAttribute
{
public MailAddressAttribute()
: base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
{
}
}
答案 0 :(得分:28)
您需要为自定义属性注册客户端验证适配器。在这种情况下,您可以使用System.Web.Mvc中现有的RegularExpressionAttributeAdapter,因为它应该与标准的regex属性完全相同。然后在应用程序开始使用时注册它:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(MailAddressAttribute),
typeof(RegularExpressionAttributeAdapter));
如果您编写需要自定义客户端验证的属性,则可以通过继承DataAnnotationsModelValidator来实现自己的适配器(另请参阅Phil Haack's blog)。
答案 1 :(得分: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-.]+$
{
}
}