views:

235

answers:

2

The Gu provides an example of how you might create a custom validator that overrides RegularExpressionAttribute (http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx).

The advantage of this is that you don't have to create a custom Model Validator (http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx).

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  A: 

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

Andersson Melo
I was given the impression, that I would get this out of the box, because I was inheriting from a built-in attribute. Is this not the case?
kim3er
Unfortunately it is not so easy =(I think that You should at least add the DataAnnotationsModelValidatorProvider.RegisterAdapter() in the global.asax
Andersson Melo
+1 Ah, excellent. Just came to exactly the same conclusion. When I have more time, I think I'll have a look at expanding the Default Factory to include derived types.
kim3er
+1  A: 

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

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