Reputation: 95
Can someone please help me figure out how to require more than one checkbox to be checked on my aspx page? I have found a few articles that show how to do this with JavaScript, but I use VB and I am not sure how to apply it.
What I would like to do is once the user clicks the submit button it will display an error if enough checkboxes have not been checked. These are not in a checkbox list but rather individual checkboxes.
Upvotes: 0
Views: 2732
Reputation: 16245
You can use a CustomValidator
for this purpose.
Within your ASPX page, you put it in your controls and the validator.
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:Label AssociatedControlID="CheckBox1" runat="server">Check this box!</asp:Label>
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:Label AssociatedControlID="CheckBox2" runat="server">And this box!</asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="You must check all of the boxes"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
After this, you can check they click Submit by checking the ServerValidate
event.
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = True ' set default
If Not CheckBox1.Checked Then
args.IsValid = False
End If
If Not CheckBox2.Checked Then
args.IsValid = False
End If
End Sub
The ServerValidateEventArgs
will allow you to specify if the user has met your criteria.
At the end of ServerValidate
event, it will return the value set in the property IsValid
to determine if it's valid or not.
Upvotes: 1