如何验证用户在CheckBoxList中选择了至少一个复选框?

时间:2009-07-18 00:09:31

标签: asp.net .net validation checkbox checkboxlist

我有一个CheckBoxList控件,我想让用户检查至少一个盒子,如果他们检查每一个,或者3个,甚至只检查一个,都无关紧要。

根据asp.net的验证控件的精神,我可以使用什么来强制执行此操作?我也在使用Ajax验证扩展器,所以如果它看起来像其他控件,而不是代码隐藏中的一些俗气的服务器验证方法,那将会很好。

<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
    <asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
    <asp:ListItem Text="Final Construction" Value="final_construction" />
    <asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
    <asp:ListItem Text="Remodel" Value="remodel" />
    <asp:ListItem Text="Color" Value="color" />
    <asp:ListItem Text="Brick" Value="brick" />
    <asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
    <asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
    <asp:ListItem Text="Fence/Screening" Value="fence_screening" />
    <asp:ListItem Text="Landscape - Front" Value="landscape_front" />
    <asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
    <asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>

7 个答案:

答案 0 :(得分:60)

这个验证服务器方面很容易,但我假设你想在客户端做这个?

JQuery可以非常轻松地执行此操作,只要您拥有所有复选框控件的共同点,以用作选择器(如类(.NET控件上的CssClass))。您可以创建一个简单的JQuery函数并将其连接到ASP.NET自定义验证程序。请记住,如果你确实去自定义验证程序路由以确保在javascript不工作的情况下检查服务器端,则不会像其他.NET验证程序那样获得免费的服务器端检查。

有关自定义验证程序的详细信息,请查看以下链接:www.asp.netMSDN

您不需要使用JQuery,它只是使javascript函数迭代并更容易查看所有复选框控件,但如果您愿意,可以使用vanilla javascript。

以下是我在Link to original

找到的示例
<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>

<asp:CustomValidator runat="server" ID="cvmodulelist"
  ClientValidationFunction="ValidateModuleList"
  ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>

// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
  var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
  var chkListinputs = chkListModules.getElementsByTagName("input");
  for (var i=0;i<chkListinputs .length;i++)
  {
    if (chkListinputs [i].checked)
    {
      args.IsValid = true;
      return;
    }
  }
  args.IsValid = false;
}

旁注:JQuery只是一个小js文件包含你需要添加到你的页面。一旦你有它,你可以使用你喜欢的所有JQuery。没有什么可以安装的,我想在Visual Studio的下一个版本中将完全支持它。

答案 1 :(得分:14)

这是一个更简洁的 jQuery 实现,它允许一个 ClientValidationFunction 用于页面上任意数量的 CheckBoxList 控件:

function ValidateCheckBoxList(sender, args) {
    args.IsValid = false;

    $("#" + sender.id).parent().find("table[id$="+sender.ControlId+"]").find(":checkbox").each(function () {
        if ($(this).attr("checked")) {
        args.IsValid = true;
        return;
        }
    });
}

这是标记:

<asp:CheckBoxList runat="server"
          Id="cblOptions" 
          DataTextField="Text" 
          DataValueField="Id" />

<xx:CustomValidator Display="Dynamic" 
              runat="server" 
              ID="cblOptionsValidator"
              ControlId="cblOptions"
              ClientValidationFunction="ValidateCheckBoxList" 
              ErrorMessage="One selection required." />

最后,自定义验证器允许客户端函数通过ID检索目标控件:

public class CustomValidator : System.Web.UI.WebControls.CustomValidator
{
    public string ControlId { get; set; }

    protected override void OnLoad(EventArgs e)
    {
        if (Enabled)
            Page.ClientScript.RegisterExpandoAttribute(ClientID, "ControlId", ControlId);

        base.OnLoad(e);
    }
}

答案 2 :(得分:3)

查看来自Rolla的4个家伙的这篇文章:

http://aspnet.4guysfromrolla.com/articles/092006-1.aspx

它们向您展示了如何为CheckBox和CheckBoxList控件创建验证器,其工作方式与其他.NET控件的RequiredFieldValidator完全相同。它具有服务器端验证和客户端验证。关于这一点很好的部分是你可以指定一个ValidationGroup,它将与ValidationSummary控件一起使用。

文章底部还有一个链接,用于下载源代码并在项目中使用它。你只需引用dll并注册控件,你就可以了。

答案 3 :(得分:1)

这是另一个可以通过GitHub上的Dado.Validators考虑​​的解决方案。

<asp:CheckBoxList ID="cblCheckBoxList" runat="server">
    <asp:ListItem Text="Check Box (empty)" Value="" />
    <asp:ListItem Text="Check Box 1" Value="1" />
    <asp:ListItem Text="Check Box 2" Value="2" />
    <asp:ListItem Text="Check Box 3" Value="3" />
</asp:CheckBoxList>

<Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />

示例codebehind.aspx.cs

btnSubmit.Click += (a, b) =>
{
    Page.Validate("vlgSubmit");
    if (Page.IsValid) {
        // Validation Successful
    }
};

https://www.nuget.org/packages/Dado.Validators/

参考:Check if a checkbox is checked in a group of checkboxes in clientside

答案 4 :(得分:1)

您可以使用CustomValidator使用一点点javascript。

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
    ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>

<script type="text/javascript">
    function checkCheckBoxList(oSrc, args) {
        var isValid = false;
        $("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
            isValid = true;
        });
        args.IsValid = isValid;
    }
</script>

对于RadioButtonList

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>

<script type="text/javascript">
    function checkRadioButtonList(oSrc, args) {
        if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
            args.IsValid = false;
        } else {
            args.IsValid = true;
        }
    }
</script>

答案 5 :(得分:0)

循环遍历ckBoxListReasons中的每个项目。每个项目都是'ListItem'类型。

ListItem将有一个名为'Selected'的属性,它是一个布尔值。选择该项目时确实如此。类似的东西:

Dim bolSelectionMade As Boolean = False
For Each item As ListItem in ckBoxListReasons.Items
 If item.Selected = True Then
  bolSelectionMade = True
 End If
Next
如果用户至少进行了一次选择,

bolSelectionMade 将设置为true。然后,您可以使用它来设置您喜欢的任何特定验证器控件的有效状态。

希望这有帮助!

理查德。

答案 6 :(得分:0)

我们也可以通过 C# 来实现

 bool Item_selected = false;
        foreach (ListItem item in checkbox.Items)
        {
            if (item.Selected == true)
            {
                Item_selected = true;
            }
        }
        if (!Item_selected )
        {
          //your message to user
          //  message = "Please select atleast one checkbox";
          
        }
相关问题