我有一个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;
}如果我在ControlToValidate=控件中添加了checkboxlistCategories,它就会爆炸!我得到的例外是:
System.Web.HttpException:由'RequiredFieldValidator8‘的ControlToValidate属性引用的控件’RequiredFieldValidator8‘
我是不是遗漏了什么?
发布于 2010-10-25 15:00:33
下面是一个更干净的jQuery实现,它允许页面上任意数量的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);
}
}发布于 2010-03-23 14:26:52
考虑到服务器端验证方法topic_ServerValidate特定地绑定到checkboxlistCategories字段,您不需要设置ControlToValidate属性。
当您添加ControlToValidate属性时,它“爆炸”的原因是您所引用的控件的类型-- CheckBoxList。当将ControlToValidate分配给任何类型的验证器时,该验证器将在执行实际验证逻辑之前自动对引用的控件执行“非空”检查。如果字段为空,则不会进行验证(即验证成功)。当然,除非您设置了ValidateWhenEmpty = true。显然,验证器不知道如何检查CheckBoxList是否为空,而是抛出异常。
在特定情况下,CustomValidator实际上只是作为非空检查,所以即使引用的控件保持为“空”,也肯定希望验证器发生。正如我在答覆的第一段所述,要达到这个目标,最简单的方法是删除违例和不必要的财产。
发布于 2010-03-23 14:41:10
只是一个建议,但是您可以使用单选按钮来代替,并定义一个组名。这将消除验证b/c的需要,在组内只能检查一个单选按钮。
https://stackoverflow.com/questions/2500637
复制相似问题