We used a custom validation attribute to validate that the collection does contain at least x item(s).
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class MinimumCollectionLengthAttribute : ValidationAttribute
{
private readonly int minimumLength;
public MinimumCollectionLengthAttribute(int minimumLength)
{
this.minimumLength = minimumLength;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var collection = value as ICollection;
if (collection is null)
{
return GetFailedResult(validationContext);
}
return collection.Count >= minimumLength ?
ValidationResult.Success
: GetFailedResult(validationContext);
}
private ValidationResult GetFailedResult(ValidationContext validationContext)
{
return string.IsNullOrWhiteSpace(ErrorMessage) ?
new ValidationResult($"The {validationContext.DisplayName} field is required.")
: new ValidationResult(ErrorMessage);
}
}
The usage is of the attribute is specified like this:
[MinimumCollectionLength(1)]