Custom DataAnnotation IsValid Not Called
<p><strong>Background</strong></p>

<p>Hello all,</p>

<p>Basically, I am writing a custom data annotation in a .NET Core Class Library that will validate that an IEnumerable has at least a certain number of elements.</p>

<hr>

<p><strong>The Problem</strong></p>

<p>For some reason, when running the validation, the IsValid is never called. I have already found a few other SO questions regarding this issue, but they all have a different problem than I do (basically, they weren't actually validating their objects). I am, however, validating my object (calling <code>Validator.TryValidateObject(...)</code>) and yet, the IsValid is never called.</p>

<p>If I use any of the out-of-the-box validation attribute (e.g. Required), it operates as expected.</p>

<hr>

<p><strong>The Code</strong></p>

<p>MinElementsAttribute.cs</p>

<pre><code>public class MinElementsAttribute : ValidationAttribute
{
    readonly int minElements;

    public MinElementsAttribute(int minElements) : base($"Collection must have a size of at least {minElements}")
    {
        this.minElements = minElements;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var list = value as IEnumerable&lt;object&gt;;

        if(list == null || list.Count() &lt; this.minElements)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }
}
</code></pre>

<p>MinElementsTests.cs</p>

<pre><code>[Fact]
public void TestValidation()
{
    var validationResults = new List&lt;ValidationResult&gt;();
    var testObject = new TestObject();

    // Should be false since I have not added anything to the list
    var isValid = Validator.TryValidateObject(testObject, new ValidationContext(testObject), validationResults);

    // Fails since isValid comes back as true because IsValid on MinElementsAttribute is never called
    Assert.False(isValid);
    Assert.NotEmpty(validationResults);
}

internal class TestObject
{
    public TestObject()
    {
        this.StringList = new List&lt;string&gt;();
    }

    [MinElements(3)]
    public List&lt;string&gt; StringList { get; set; }
}
</code></pre>

<hr>

<p><strong>Edit: The Solution</strong></p>

<p>Please see the accepted answer for the solution. I wanted to add this to also note that by changing the inheritance to be from RequiredAttribute rather than ValidationAttribute, you can enforce the validation of all object properties implicitly.</p>