zid*_*dar 20 regex asp.net asp.net-mvc client-side-validation data-annotations
为了保持我的模型验证干净,我想实现我自己的验证属性,比如PhoneNumberAttribute和EmailAttribute.其中一些可以有利地实现为继承的简单类RegularExpressionAttribute.
但是,我注意到这样做会破坏这些属性的客户端验证.我假设有某种类型的绑定在某处失败.
我能做些什么来让客户端验证工作?
代码示例:
public sealed class MailAddressAttribute : RegularExpressionAttribute
{
public MailAddressAttribute()
: base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
{
}
}
Run Code Online (Sandbox Code Playgroud)
小智 29
您需要为自定义属性注册客户端验证适配器.在这种情况下,您可以使用System.Web.Mvc中现有的RegularExpressionAttributeAdapter,因为它应该与标准的regex属性完全相同.然后在应用程序开始使用时注册:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(MailAddressAttribute),
typeof(RegularExpressionAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)
如果您编写需要自定义客户端验证的属性,则可以通过继承DataAnnotationsModelValidator来实现自己的适配器(另请参阅Phil Haack的博客).
延伸正确的答案
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-.]+$
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5327 次 |
| 最近记录: |