requiredfield检查转发器中的asp.net复选框?

时间:2012-03-05 00:18:02

标签: javascript asp.net c#-3.0 validation

如何在发布asp.net页面之前对每个复选框进行必填项检查?因此,至少需要检查一个复选框。

ASPX

                                                                                                                 

    <asp:Button ID="Submit" Text="Submit" runat="server" OnClick="Submit_Click" />

1 个答案:

答案 0 :(得分:1)

对于选中至少一个复选框的一组复选框,我所知道的最简单方法是使用<asp:CustomValidator />。编写JavaScript验证函数(以验证复选框并确保至少检查一个)并将其分配给<asp:CustomValidator />

示例标记:

<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<asp:CheckBox ID="CheckBox4" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Check at least one" ClientValidationFunction="atLeastOneIsChecked"></asp:CustomValidator>

示例JavaScript:

function atLeastOneIsChecked(sender, args) {
    var chk1 = document.getElementById('<%=CheckBox1.ClientId %>').checked;
    var chk2 = document.getElementById('<%=CheckBox2.ClientId %>').checked;
    var chk3 = document.getElementById('<%=CheckBox3.ClientId %>').checked;
    var chk4 = document.getElementById('<%=CheckBox4.ClientId %>').checked;

    args.IsValid = (chk1 || chk2 || chk3 || chk4);
    return args.IsValid;
}