遗传性RegularEx pressionAttribute ASP.NET MVC数据注解客户端验证 [英] ASP.NET MVC data annotations client side validation with inherited RegularExpressionAttribute

查看:101
本文介绍了遗传性RegularEx pressionAttribute ASP.NET MVC数据注解客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要继续我的模型验证干净的,我想实现我自己的验证属性,如 PhoneNumberAttribute EmailAttribute 。其中的一些可以可靠地被实现为简单的类,继承 RegularEx pressionAttribute

不过,我注意到,这样做违反这些属性的客户端验证。我假设有某种类型绑定的失败的地方。

任何想法,我能做些什么来获得客户端验证工作?

code例如

 公共密封类MailAddressAttribute:RegularEx pressionAttribute
{
    公共MailAddressAttribute()
        :基地(@^ [A-ZA-Z0-9 ._%+ - ] + @ [A-ZA-Z0-9 .-] + \\ [A-ZA-Z] {2,4} $ )
    {
    }
}


解决方案

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

  DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof运算(MailAddressAttribute)
    typeof运算(RegularEx pressionAttributeAdapter));

您应该​​编写需要自定义客户端验证一个属性,您可以通过从的 DataAnnotationsModelValidator (见菲尔哈克的博客)。

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}$")
    {
    }
}

解决方案

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:

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

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).

这篇关于遗传性RegularEx pressionAttribute ASP.NET MVC数据注解客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆