我有一个CheckBoxList,我正在尝试验证是否至少选中了一个复选框。

标记:

<asp:CustomValidator ID="RequiredFieldValidator8" ValidationGroup="EditArticle"
    runat="server" ErrorMessage="At least one Category is required."
    OnServerValidate="topic_ServerValidate" />
<asp:CheckBoxList id="checkboxlistCategories" runat="server"></asp:CheckBoxList>


后台代码:

protected void topic_ServerValidate(object source, ServerValidateEventArgs args)
{
    int i = 0;
    foreach (ListItem item in checkboxlistCategories.Items)
    {
        if (item.Selected == true)
            i = i + 1;
    }
    if (i == 0)
        args.IsValid = false;
    else
        args.IsValid = true;
}


如果我在CustomValidator控件中添加ControlToValidate =“ checkboxlistCategories”,它会爆炸!我得到的异常是:


System.Web.HttpException:控制“ checkboxlistCategories”,由“ RequiredFieldValidator8”的ControlToValidate属性引用


我想念什么吗?

最佳答案

这是一个更干净的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);
 }
}

09-25 21:12