使用CustomValidator for CheckBox ASP.NET

时间:2014-10-23 10:35:45

标签: asp.net visual-studio-2013

您好我真的很难在我的复选框中设置客户验证器,以确保用户必须至少检查一个。

我看了看这个网站,阅读并试过但似乎没有任何效果。我也不确定服务器端的代码是什么,因为我还在学习初学者,所以任何帮助都会非常感激。

我可以说我对C#没有任何线索所以你建议的任何代码都需要是ASP.NET / VisualBasic

这些是我的复选框HMTL方..

Male:
    <asp:CheckBox ID="cbMale" runat="server" groupname="sexB"/> 
    <br />
Female:
    <asp:CheckBox ID="cbFemale" runat="server" groupname="sexB"/>

谢谢

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



    If Page.IsPostBack = False Then

        Dim dsData1 As New DataSet
        dsData1 = tableData()


        DDList.DataSource = dsData1
        DDList.DataValueField = "code"
        DDList.DataTextField = "description"
        DDList.DataBind()
        DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
        DDList.SelectedIndex = 0


        Dim dsData2 As New DataSet
        dsData2 = tableData2()


        DDList2.DataSource = dsData2
        DDList2.DataValueField = "code"
        DDList2.DataTextField = "description"
        DDList2.DataBind()
        DDList2.Items.Insert(0, New ListItem(String.Empty, String.Empty))
        DDList2.SelectedIndex = 0
    Else


        Dim sexSelect1 As String = ""

        If cbMale.Checked = True Then
            sexSelect1 = "M"
        Else
            sexSelect1 = "F"
        End If


        Dim testInsert As String = dataInsertTable(nameB.Text, ageB.Text, sexSelect1,  DDList.SelectedValue, DDList2.SelectedValue)


    End If



End Sub

1 个答案:

答案 0 :(得分:0)

这是一种常见的情况,您可以按照本示例中提到的方式使用customvalidator:

http://www.aspsnippets.com/Articles/Validate-ASPNet-CheckBoxList-at-least-one-CheckBox-checked-using-Custom-Validator.aspx

IT使用Javascript进行验证。

在头部

中添加以下内容
 <script language = javascript >
        function ValidateSE(source, args) {
            var chkSEMAFF = document.getElementById('<%= CbSe.ClientID%>');
            var chkSEMAFFX = chkSEMAFF.getElementsByTagName("input");
            for (var i = 0; i < chkSEMAFFX.length; i++) {
                if (chkSEMAFFX[i].checked) {
           args.IsValid = true;
              return;
        }
      }
     // alert("Choose either male or female");
      args.IsValid = false;

}
</script>

在表单标记

之间添加以下内容
 <div>

    <asp:CheckBoxList ID="CbSe" runat="server" ClientIDMode="Static">

   <asp:ListItem Text="male" Value="male" /> 
   <asp:ListItem Text="female" Value="female" />
    </asp:CheckBoxList>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    <asp:customvalidator runat="server" forecolor="Red" id="cuse" clientvalidationfunction="ValidateSE" errormessage="Please select either male or female"></asp:customvalidator>
  </div>

将以下内容添加为

后面的代码
 Dim sexSelect1 As String = ""

            If CbSe.SelectedValue = "male" Then
                sexSelect1 = "M"
            Else
                sexSelect1 = "F"
            End If