开发者

Custom Validation on group of checkboxes

开发者 https://www.devze.com 2023-02-04 04:29 出处:网络
I\'m trying to understand how I can validate a group of checkboxes. My Model: [MinSelected(MinSelected = 1)]

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 som开发者_高级运维eone help me out with this?


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消