How to validate 2 checkboxes to make sure at least one is checked

I noticed that one of the benifits of RequiredFieldValidator is that you no longer have to post back to the server to do the validation however with the checkbox control, the only way I got validation to work was to do an If statement.  I have 2 checkboxes and if neither of the 2 were checked, then the user gets an error message (label).  But in order to do so, I had to put this if statement on submission of the page so it posts thus giving me the validation error.

I don't see how you can use RequiredFieldValidator if you have 2 checkboxes and at least one checkbox has to be checked but not both can be checked at the same time.  If both had to be checked then I could use RequiredFieldValidator but that isnt' the case

so is there a way to do a validation client?

Here is how I did it but this requires a post and I thought that one of the benefits of .Net was to get around having to post back to validate sometimes....

Sub Button_Click( s As Object, e As EventArgs )
      Dim Conn as SQLConnection
      Dim strInsert as String
      Dim cmdSQL as SQLCommand
      If Not (Full_Time.Checked OR Part_Time.Checked) Then
      Error_BothChecked.Text="<FONT FACE=""ARIAL"" COLOR=RED SIZE=2><B>You must check <U>at least one</U> checkbox</B></FONT>"
      Else If (Full_Time.Checked AND Part_Time.Checked) Then
      Error_BothChecked.Text="<FONT FACE=""ARIAL"" COLOR=RED SIZE=2><B>You must <U>only check one</U> checkbox</B></FONT>"

End Sub

maybe this is the only way in this circumstance but I think there must be a way to do this with some of the checkbox properties

I thought of using a checkboxlist but this seems to work fine already in reference to how I did it above

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

I would always use javascript.
Let's say that you have a button "btGo" that will submit the checkboxes.

Add this to your page_load:

btGo.Attributes.Add("onclick") = "javascript:return checktheboxes();"

Then in your aspx page add this javascript:
<script language="javascript">
  function checktheboxes()
    var f=document.forms(0).fulltime.checked;
    var p=document.forms(0).parttime.checked;
    if (f||p) {return true;} else
    {alert('You need to check at least one checkbox!');}
    return false;

This will prevent the postback when nothing is checked as well.

btw: The names of the checkboxes in the javascript are CASE-sensitive.
Change them if nessacary.
Ralf KlattEmployee in Civil ServiceCommented:

roverm is right with his JavaScript statement -> I haven't tested his code but it looks that this can work out.

But tell me dba123, why are you using CheckBoxes for what you're doing? 2 RadioButtons would do the job without annoying the user with error messages -> when I would see your option I would probably check both boxes -> to inform that I'm available for fulltime as well as for parttime ...

There is no validator to use for checkboxes -> only -> you find a custom control or you write a custom control yourself -> doing that would mean that infact you build a poor repliaction of a RadioButtonList. A thinkable workarround would be to place two hidden textfields both set to zero by default -> if any checkbox is checked the corresponding textfield must be set to 1 -> but then again you're in need of a postback:

This here is an example on how a CompareValidator works:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="cbvalidator.aspx.vb" Inherits="exex002.cbvalidator"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
            <form runat="server" ID="Form1">
                  <table border="0" bgcolor="#b0c4de">
                  <P>Compare two values</P>
                        <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>&nbsp;=
                        <asp:TextBox id="TextBox2" runat="server"></asp:TextBox></P>
                  <P><asp:Button Text="Validate" runat="server" ID="Button1" NAME="Button1" /></P>
                        <asp:CompareValidator id="compval" Display="dynamic" ControlToValidate="TextBox1" ControlToCompare="TextBox2" ForeColor="red" Type="String" EnableClientScript="false" Text="Validation Failed!" runat="server" /></P>

What I found for you ---> if you're really interested in building a custom control <--- is a C# sample -> even though you asked for VB code and might not be able to read it ---> from the author's statements you might get an impression! ... ------->

Best regards, Raisor

Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

The approach of Raisor seams to be, in part :-), correct.

"A thinkable workarround would be to place two hidden textfields both set to zero by default -> if any checkbox is checked the corresponding textfield must be set to 1 -> but then again you're in need of a postback"

I don't think it would need a postback, you only need to add a compare validator binded to both textboxes and change the operator property to 'not equal'

And default value the textboxes to "" (same for unchecked) and if checked to something else, so it will alway validate that at least one and only one of the checkboxes is checked.
My code will work ;-)

I don't think that using radiobuttons will be an option because dba123 asked for 'at least one'...
A grouped radiobuttonlist won't do that.
sorry for the typo --> set de default value to "x" or wahtever value diferent to a empty string
dba123Author Commented:
Ok, well I guess there are 2 things:

1) I don't know JavaScript well
2) I am trying to learn ASP.Net therefore I am trying to keep from  having to use a non ASP.Net control but as you said I don't have much of a choice here.  I think even if I use a radio button, I have to post back in order to produce a validation error

So I could use radio buttons instead of a checkbox and just set one of the radio buttons to be the selected value when the page is rendered but I'd rather have checkboxes so that they are blank and force the user to really look at th at choice and make the right one.  Basically they are employees at our company and know if they are full-time or part-time to answer your question or concern on that one

I guess I may not have a choice and must use JavaScript in this case.  I know that ASP.Net in the backend uses JavaScript to automate a few things as well which makes ASP.Net a bit better in one aspect to classic ASP.

I also tried using an ASP image tag <img id="someide" src="..image/myimage.jpg" onmouseover="myfuncion()">

but of course it cannot call a sub function from this I think, I just get an error and don't even know if this is possible using an img tag like this

I just want a way that either a user can click on an image (preferably an image rather than a plain button with text) or mouseover and image and it invokes my function without any post.  And I guess if JavaScript is the best here (since it is of course client side code) then that makes sense but I was just hoping for something in .Net since I am learning it.  

Maybe using JavaScript and .Net together is powerful and even the norm....I am trying to be consistent.  To me I feel that if .Net is very powerful, you should be able to do all of it in VB and controls, etc. from the .Net classes and not even touch JavaScript but maybe I am totally wrong on that point and missing the whole point that this is the norm, that using JavaScript with ASP is absolutely necessary for truly performing all necessary tasks for ASP.

fill me in on the standards here and in general practices with ASP & JavaScript because I still shy away from using JavaScript.  I will eventually dwelve into C# but now I am starting in ASP.Net moving away from classic ASP
>> onmouseover="myfuncion()" will call a clientside function. That's why it throws the error.

Javascript and .NET go hand in hand. Even Microsoft used it to postback all information on a site to the server.

I always use this as a rule:
If possible PREVENT a postback to the server.

Postbacks can be quite annoying the users.

If you want to avoid java-script, here is another work-around.

Create your own custom control that contains the check boxes.  Use a property value to hold the state


default it to 0
if 1st checkbox is checked, set to 1
if second is checked set it to 2
if both checked set to 3
if third checked set to 4
and so on...

then just set the RequiredFieldValidator to check for a non-zero condition on the custom control

hope that helps
Ralf KlattEmployee in Civil ServiceCommented:

@patriziop ... it's good to see that you understood my approach and even proved this by repeating it! About the postback event -> have you ever tried it? You should know that you have to set autopostback to true when you want to catch the OnSelectedChange event :-))

@dba123 ... You will find out soon that the post back event is a great chance for a .NET developer -> there are situations where you want them to happen (but they don't) so that you have to add java script to do a page refresh ... when you look at any web site with your internet explorer and right click to see the source code in text format -> then you will realise that the basic functionality of that site depends on javacript -> by default!
What I have here is a little piece of code you should try to test ;-))

File Name: cbnew.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="cbnew.aspx.vb" Inherits="YourSite.cbnew"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="">
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <asp:CheckBox id="CheckBox1" style="Z-INDEX: 101; LEFT: 288px; POSITION: absolute; TOP: 80px" runat="server" AutoPostBack="True" Text="Full Time"></asp:CheckBox>
                  <asp:CheckBox id="CheckBox2" style="Z-INDEX: 102; LEFT: 410px; POSITION: absolute; TOP: 80px" runat="server" AutoPostBack="True" Text="Part Time"></asp:CheckBox>
                  <asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 358px; POSITION: absolute; TOP: 123px" runat="server" Text="Submit" Visible="False"></asp:Button>
                  <asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 291px; POSITION: absolute; TOP: 42px" runat="server">Please check appropriate value</asp:Label>

File Name: cbnew.aspx.vb

Public Class cbnew
    Inherits System.Web.UI.Page
      Protected WithEvents CheckBox1 As System.Web.UI.WebControls.CheckBox
      Protected WithEvents CheckBox2 As System.Web.UI.WebControls.CheckBox
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents Button1 As System.Web.UI.WebControls.Button

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      End Sub
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Hier Benutzercode zur Seiteninitialisierung einfügen
    End Sub

      Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
            Select Case CheckBox1.Checked
                  Case True
                        CheckBox2.Enabled = False
                        Button1.Visible = True
                  Case Else
                        CheckBox2.Enabled = True
                        Button1.Visible = False
            End Select
      End Sub

      Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged
            Select Case CheckBox2.Checked
                  Case True
                        CheckBox1.Enabled = False
                        Button1.Visible = True
                  Case Else
                        CheckBox1.Enabled = True
                        Button1.Visible = False
            End Select
      End Sub
End Class

Best regards, Raisor

Is good to have someone to discus this topics in a good manner, but I test it before submiting my comment :-)
And is not need for the onSelectChanged event on the server, just put 2 checkboxes, 2 textboxes and 1 comparevalidator in a web form and add this code to the page load event

       If Not Page.IsPostBack Then
            TextBox1.Text = CStr(False)
            TextBox2.Text = CStr(False)
            TextBox1.Visible = False
            TextBox2.Visible = False

            'the following lines will add client java script support for the server controls
            CheckBox1.Attributes.Add("language", "jscript")
            CheckBox1.Attributes.Add("onclick", "TextBox1.value=this.checked;")
            CheckBox2.Attributes.Add("language", "jscript")
            CheckBox2.Attributes.Add("onclick", "TextBox2.value=this.checked;")
        End If

Configure also, the comparevalidator control to compare the 2 textboxes for a Non Equal type of compare, as i quoted above and it will work
It is simpler, it does not postback, and works! But you must revalidate the posted information on the server too. A best practice to avoid a manual post of data to your web form.

The client validation is done to avoid innecesary postbacks to the server, reducing its workload (scalability) and the server side validation is for security and for those cases where the validation can't be made on client side because it must be a comparison to serverside data.
Ralf KlattEmployee in Civil ServiceCommented:

If it is done this way it will really work ---> this is your solution dba123:

            If Not Page.IsPostBack Then
                  TextBox1.Text = CStr(False)
                  TextBox2.Text = CStr(False)
                  TextBox1.Style.Add("display", "none")
                  TextBox2.Style.Add("display", "none")
                  CheckBox1.Attributes.Add("language", "jscript")
                  CheckBox1.Attributes.Add("onclick", "TextBox1.value=CheckBox1.checked;")
                  CheckBox2.Attributes.Add("language", "jscript")
                  CheckBox2.Attributes.Add("onclick", "TextBox2.value=CheckBox2.checked;")
            End If

The form with the CompareValidator control could look like this:

            <form id="Form1" method="post" runat="server">
                  <asp:CheckBox id="CheckBox1" style="Z-INDEX: 101; LEFT: 288px; POSITION: absolute; TOP: 80px" runat="server" Text="Full Time"></asp:CheckBox>
                  <asp:CheckBox id="CheckBox2" style="Z-INDEX: 102; LEFT: 410px; POSITION: absolute; TOP: 80px" runat="server" Text="Part Time"></asp:CheckBox>
                  <asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 358px; POSITION: absolute; TOP: 123px" runat="server" Text="Submit"></asp:Button>
                  <asp:TextBox id="TextBox1" style="Z-INDEX: 105; LEFT: 313px; POSITION: absolute; TOP: 178px" runat="server"></asp:TextBox>
                  <asp:TextBox id="TextBox2" style="Z-INDEX: 106; LEFT: 312px; POSITION: absolute; TOP: 217px" runat="server"></asp:TextBox>
                  <asp:CompareValidator id="CompareValidator1" style="Z-INDEX: 109; LEFT: 291px; POSITION: absolute; TOP: 38px" runat="server" ErrorMessage="CompareValidator" ControlToCompare="textbox1" ControlToValidate="textbox2" Operator="NotEqual">One field should be checked!</asp:CompareValidator>

Best regards, Raisor
Ralf KlattEmployee in Civil ServiceCommented:

@patriziop -> you were right about the "no-post-back-necessity" before validation is successful -> I have already worked with this technology but with a different approach I needed a postback to process client data to server so I had to simulate a postback by firing some javascript into the page ;-)) … if you set TextBoxes to Invisible they are not found by the client script -> that’s done with: TextBox1.Style.Add("display", "none") … if you use “this” instead of the controls name you’ll receive an “undefined” -> not as an error but as result in your textbox (instead of True or False) …

Best regards, Raisor
No prob!
dba123, any progress here?
Ralf KlattEmployee in Civil ServiceCommented:

I like your point of view and am still happy to have tried to apply your approach! I will use this solution myself in further projects!

Best regards, Raisor
dba123Author Commented:
<edited by Yensidmod>

Now about my original question.  I think I realize that I need to start incorporating more JavaScript.  I don't like postbacks for any validation, it simply is a waste of energy both for the programmer and the system that runs the app.  So I will dwelve more on that side when needed.

I have been busy in my job as a DBA and of course have a life at home so last night was not able to get back to this but I will tonight and let you know if any of your code samples work with my code when I try to encorporate.
Also: this is what dba123 wrote:
>> I think I realize that I need to start incorporating more JavaScript.

So if I'm not mistaking a solution will be used!
I have deleted all non technical comments.  Question has been PAQed and 500 points refunded.  If anyone wants to discussed this further, post here

Experts Exchange Moderator

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
In reading through this question, it appears to me as though the suggestion that a solution to the problem is here is an accurate suggestion that got lost amid a bunch of crap. One hopes that the participants will pay a little more attention to with particular attention paid to the sections regarding professionalism and being very careful about criticism of others and their comments.

Nonetheless, I have created the following. Please post there.

roverm: (deleted by roverm request)

EE Admin
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.