在 C# 中验证复选框和单选按钮

2024-04-11

我正在使用 C# 进行编码!

下面是我的复选框和单选按钮的 html

  <input type="radio" style="float: left;" name="documents" id="Checkbox9" value="yes"
                        runat="server" />
                    <label style="width: 35px!important;" class="checkbox">
                        <%=GetResourceString("c_HSGStudent")%>
                    </label>
                    <input type="radio" style="float: left;" name="documents" id="Checkbox10" value="no"
                        runat="server" />
                    <label style="width: 25px!important;" class="checkbox">
                        <%=GetResourceString("c_HSGParent")%>
                    </label>
                    <input type="radio" style="float: left;" cheked name="documents" id="Radio1" value="yes"
                        runat="server" />
                    <label style="width: 35px!important;" class="checkbox">
                        <%=GetResourceString("c_HSGStudent")%>
                    </label>
                    <input type="radio" style="float: left;" name="documents" id="Radio2" value="no"
                        runat="server" />
                    <label style="width: 25px!important;" class="checkbox">
                        <%=GetResourceString("c_HSGParent")%>
                    </label>

您可以看到我有两个复选框和两个单选按钮,我的问题是在提交按钮上单击我想检查用户是否至少选中了一个复选框或单选按钮。如果我们能够拥有像 (customvalidator) 这样的 .NET 解决方案,那就太好了。

请建议!

Thanks


首先,将 CustomValidator 添加到您的页面...

<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true" 
    OnServerValidate="CheckBoxRequired_ServerValidate" 
    OnClientValidate="CheckBoxRequired_ClientValidate">*</asp:CustomValidator> 

然后,您可以使用简单的 jquery 调用从客户端函数验证它们...

<script type="text/javascript>

function CheckBoxRequired_ClientValidate(sender, e) 
{ 
    e.IsValid = $("input[name='documents']").is(':checked'); 
} 

</script>

用于服务器端验证的代码隐藏...

protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e) 
{ 
    e.IsValid = Checkbox9.Checked || Checkbox10.Checked || Radio1.Checked || Radio2.Checked;
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中验证复选框和单选按钮 的相关文章

随机推荐