none
Validation Attribute doesn't work with List<T> RRS feed

  • Question

  • Hi,

    I want to inherit from List<T> and create a custom validation attribute for this new class. But it never goes into the validation within the attribute.

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class MyAttribute: ValidationAttribute{...}


    [MyAttribute]
    public class MyList<T>:List<T>{...}

    Someone can help?

    Thanks


    Friday, May 4, 2018 2:25 PM

All replies

  • That depends on how you are doing the validation. If the object that is being validated is declared as being of type List<T> and not MyList<T>, only the attributes in List<T> will be used even if the object contains a MyList<T> at run time. The attributes are not propagated in a polymorphic way through inheritance like the methods in the class.

    Edit: Well, if you do the validation yourself, you could read the attributes on the inherited class. You would just reflect on theObject.GetType() instead of typeof(theClass). But you can't do this if you can't modify the validation code.

    Friday, May 4, 2018 3:32 PM
    Moderator
  • Hello,

    >>But it never goes into the validation within the attribute.

    You need to use reflection to fetch attributes as below code.

        var customAttributes = (MyAttribute[])typeof(MyList<object>).GetCustomAttributes(typeof(MyAttribute), true);
                if (customAttributes.Length > 0)
                {
                    var myAttribute = customAttributes[0];
                    // TODO: Do something with the value
                }

    Best Regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 7, 2018 9:07 AM
    Moderator
  • Do you mean call this code in the Controller for example?

    I think is gonna be better wrap the list in a new class.

    Monday, May 7, 2018 12:58 PM
  • Hello s19,

    The validation rule usually is built inside framework, Like RequiredAttribute in Entity framework. the process of validation has been designed by EF developers. For study purpose you just need to ensure the custom rules must be executed.

    Best Regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, May 9, 2018 9:43 AM
    Moderator