Field annotated multiple times by the same attribute

Posted by Jaroslaw Waliszko on Stack Overflow See other posts from Stack Overflow or by Jaroslaw Waliszko
Published on 2014-08-20T20:58:53Z Indexed on 2014/08/22 10:20 UTC
Read the original article Hit count: 151

For my ASP.NET MVC application I've created custom validation attribute, and indicated that more than one instance of it can be specified for a single field or property:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class SomeAttribute: ValidationAttribute

I've created validator for such an attribute:

public class SomeValidator : DataAnnotationsModelValidator<SomeAttribute>

and wire up this in the Application_Start of Global.asax

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof (SomeAttribute), typeof (SomeValidator));

Finally, if I use my attribute in the desired way:

[SomeAttribute(...)]  //first
[SomeAttribute(...)]  //second
public string SomeField { get; set; }

when validation is executed by the framework, only first attribute instance is invoked. Second one seems to be dead. I've noticed that during each request only single validator instance is created (for the first annotation).

How to solve this problem and fire all attributes?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about asp.net-mvc