Custom Validation on group of checkboxes

纵饮孤独 提交于 2019-12-25 02:22:51

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/4661418/custom-validation-on-group-of-checkboxes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!