dcolumbus
dcolumbus

Reputation: 9722

Custom Validation on group of checkboxes

I'm trying to understand how I can validate a group of checkboxes.

My Model:

[MinSelected(MinSelected = 1)]
public IList<CheckList> MealsServed { get; set; }

I'd like to be able to create a custom validator that will ensure that at least 1 (or some other number) checkbox is selected. If not, display an ErrorMessage.

#region Validators

public class MinSelectedAttribute : ValidationAttribute
{
    public int MinSelected { get; set; }

    // what do I need to do here?
}

Could someone help me out with this?

Upvotes: 0

Views: 797

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could override the IsValid method and ensure that the collection contains at least MinSelected items with IsChecked equal to true (I suppose that this CheckList class of yours has an IsChecked property):

public class MinSelectedAttribute : ValidationAttribute
{
    public int MinSelected { get; set; }

    public override bool IsValid(object value)
    {
        var instance = value as IList<CheckList>;
        if (instance != null)
        {
            // make sure that you have at least MinSelected
            // IsChecked values equal to true inside the IList<CheckList>
            // collection for the model to be valid
            return instance.Where(x => x.IsChecked).Count() >= MinSelected;
        }
        return base.IsValid(value);
    }
}

Upvotes: 1

Related Questions