自定义验证的复选框组 [英] Custom Validation on group of checkboxes

查看:131
本文介绍了自定义验证的复选框组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明白我怎么可以验证一组复选框。

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

我的模型:

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

我希望能够创建一个自定义的验证,这将确保至少有1(或其他数字)复选框被选中。如果没有,显示的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?

推荐答案

您可以覆盖的的IsValid 方法,并确保该集合包含具有器isChecked MinSelected 项目>等于真正(我想,这个核对清单类你有一个器isChecked 属性):

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

这篇关于自定义验证的复选框组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆