Custom DataAnnotations Validator Derived from RegularExpressionAttribute

ぃ、小莉子 提交于 2019-12-19 08:05:32

问题


The Gu provides an example of how you might create a custom validator that overrides RegularExpressionAttribute .

The advantage of this is that you don't have to create a custom Model Validator but I can't get it to work.

Given the following code:

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

This works:

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

But this doesn't:

[Name]

Have I misunderstood an aspect of Scott's example or is the example flawed in that MVC doesn't support derived types out of the box, so actually I will have to create a a corresponding ModelValidator?


回答1:


Cracked it! Add the following to Global.asax.cs Application_Start()

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



回答2:


If u wanna a client validation, you should Register a server-side adapter for remote validation.

See here: http://msdn.microsoft.com/en-us/magazine/ee336030.aspx

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



来源:https://stackoverflow.com/questions/2689444/custom-dataannotations-validator-derived-from-regularexpressionattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!