开发者

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 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜