简体   繁体   English

如何验证内容页面中的复选框列表?

[英]How to validate checkbox list in content page?

I am taking a checkbox list in content page of a master page by which i can select multiple values and save in the database. 我在母版页的内容页中显示了一个复选框列表,通过它可以选择多个值并保存在数据库中。 How to confirm that minimum one of the checkboxes r selected at the time of clicking the submit button. 如何确认在单击“提交”按钮时至少选中了一个复选框。

You can do like below. 您可以像下面这样。

It does not matter in JavaScript that where control are either or content page or master page 在JavaScript中,控件位于内容页面或母版页中并不重要

<asp:CheckBoxList ID="chkModuleList"runat="server" />

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

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

Update: Or you can go through this approach: Put any css-class say company . 更新:或者您可以采用这种方法:将任何css-class company说成是company You can go through below. 您可以在下面浏览。

There is a :checked ( http://api.jquery.com/checked-selector/ ) selector you can use : 您可以使用: :checkedhttp://api.jquery.com/checked-selector/ )选择器:

<script>
    $(document).ready(function() {
        $(".company input").click(function() {
            var cnt = $(".company input:checked").length;
            if (cnt == 0)
            {
               // none checked
            }
            else
            {
               // any checked
            }
        });
    });
</script>

You may want to add (or use) an id on the container of these checkbox, to optimize selector speed. 您可能想在这些复选框的容器上添加(或使用一个ID),以优化选择器的速度。

As for asp.net messing up client ids on controls, you can use 至于asp.net弄乱控件上的客户端ID,则可以使用

$('<%= MyControl.ClientID %>')

References: 参考文献:

Dado.Validators , a library on GitHub, handles this very nicely too. 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" />

Example codebehind.aspx.cs 示例代码behind.aspx.cs

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM