【问题标题】:Custom DataAnnotations Validator Derived from RegularExpressionAttribute从 RegularExpressionAttribute 派生的自定义 DataAnnotations 验证器
【发布时间】:2010-04-22 09:03:05
【问题描述】:

The Gu provides an example 了解如何创建覆盖 RegularExpressionAttribute 的自定义验证器。

这样做的好处是您不必create a custom Model Validator,但我无法让它工作。

给定以下代码:

public class NameAttribute : RegularExpressionAttribute {
    public NameAttribute()
        : base(@"^[\w\s\-\']+$") {
    }
}

这行得通:

[RegularExpression(@"^[\w\s\-\']+$")]

但这不是:

[Name]

我是否误解了 Scott 示例的某个方面,或者该示例是否存在缺陷,因为 MVC 不支持开箱即用的派生类型,所以实际上我必须创建一个相应的 ModelValidator?

【问题讨论】:

    标签: asp.net-mvc validation data-annotations


    【解决方案1】:

    破解了!将以下内容添加到 Global.asax.cs Application_Start()

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

    【讨论】:

    • 太棒了!也快疯了!
    【解决方案2】:

    如果你想要一个客户端验证,你应该注册一个服务器端适配器以进行远程验证。

    请看这里: http://msdn.microsoft.com/en-us/magazine/ee336030.aspx

    这里: http://bradwilson.typepad.com/blog/2010/01/remote-validation-with-aspnet-mvc-2.html

    【讨论】:

    • 给我的印象是,我会开箱即用,因为我是从内置属性继承的。不是这样吗?
    • 不幸的是,这并不容易=(我认为您至少应该在 global.asax 中添加 DataAnnotationsModelValidatorProvider.RegisterAdapter()
    • +1 啊,太好了。刚刚得出了完全相同的结论。当我有更多时间时,我想我会看看扩展默认工厂以包含派生类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2023-03-03
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多