Custom DataAnnotations validator derived from RegularExpressionAttribute

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

The advantage of this is that you do not need to create a custom template validator , but I cannot make it work.

Given the following code:

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

It works:

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

But this is not so:

 [Name] 

Did I not understand one aspect of Scott's example, or is it an example that MVC does not support derived types from the box, so will I actually have to create the corresponding ModelValidator?

+4
source share
2 answers

Hacked it! Add Application_Start () to Global.asax.cs

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)); 
+10
source

If you want to verify the client, you need to register the server adapter for remote verification.

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

+1
source

Source: https://habr.com/ru/post/1307636/


All Articles