1

This question is somewhat of a follow-up to this question about making a custom validation for the length of an ICollection.

I created a custom DataAnnotation class according to the post I referenced, which looks like this:

/// <summary>
/// Require a minimum length, and optionally a maximum length, for any IEnumerable
/// </summary>
sealed public class CollectionMinimumLengthValidationAttribute : ValidationAttribute
{
    const string errorMessage = "{0} must contain at least {1} item(s).";
    const string errorMessageWithMax = "{0} must contain between {1} and {2} item(s).";
    int minLength;
    int? maxLength;          

    public CollectionMinimumLengthValidationAttribute(int min)
    {
        minLength = min;
        maxLength = null;
    }

    public CollectionMinimumLengthValidationAttribute(int min,int max)
    {
        minLength = min;
        maxLength = max;
    }

    //Override default FormatErrorMessage Method  
    public override string FormatErrorMessage(string name)
    {
        if(maxLength != null)
        {
            return string.Format(errorMessageWithMax,name,minLength,maxLength.Value);
        }
        else
        {
            return string.Format(errorMessage, name, minLength);
        }
    }  

    public override bool IsValid(object value)
    {
        IEnumerable<object> list = value as IEnumerable<object>;

        if (list != null && list.Count() >= minLength && (maxLength == null || list.Count() <= maxLength))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I have a property in my model class that uses the form validation as follows. I've provided another variable to be referenced later:

// A list of items
[CollectionMinimumLengthValidation(1)]
public ICollection<Item> ItemList { get; set; }

// The name of the list
[Required]
public string ListName { get; set;}

In the application's current state, if I attempt to submit the form with the Items ICollection empty, I get an error that my model state is invalid, then we are returned to the form page with the ValidationMessage popped up in red:

if (ModelState.IsValid)
{
    // does not reach this point
}

// goes here instead
return View(itemModel);

This is technically correct, but I would like my form to be blocked from a submission attempt if the ICollection is empty. If I attempt to submit the form with the string for ListName empty, the form doesn't submit and the ValidationMessage pops up immediately.

Is there a way for me to implement that with the ICollection custom validation?

0 Answers0