Solved

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

Posted on 2003-12-09
20
2,029 Views
Last Modified: 2012-06-27
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.Visible=True
      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.Visible=True
      Error_BothChecked.Text="<FONT FACE=""ARIAL"" COLOR=RED SIZE=2><B>You must <U>only check one</U> checkbox</B></FONT>"
      
      Else............

      
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

0
Comment
Question by:dba123
  • 6
  • 5
  • 4
  • +4
20 Comments
 
LVL 12

Expert Comment

by:roverm
ID: 9910454
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;
  }
</script>

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

D'Mzz!
RoverM
0
 
LVL 12

Expert Comment

by:roverm
ID: 9910457
btw: The names of the checkboxes in the javascript are CASE-sensitive.
Change them if nessacary.
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9912077
Hi,

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">
<HTML>
      <body>
            <form runat="server" ID="Form1">
                  <table border="0" bgcolor="#b0c4de">
                  </table>
                  <P>Compare two values</P>
                  <P>
                        <br>
                        <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>
                  <P>
                        <asp:CompareValidator id="compval" Display="dynamic" ControlToValidate="TextBox1" ControlToCompare="TextBox2" ForeColor="red" Type="String" EnableClientScript="false" Text="Validation Failed!" runat="server" /></P>
            </form>
      </body>
</HTML>


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! ... ------->       http://www.dotnetjunkies.com/Article/ECCCD6A6-B312-41CB-87A1-10BB5D641D20.dcik



Best regards, Raisor

0
 
LVL 3

Expert Comment

by:patriziop
ID: 9912348
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.
0
 
LVL 12

Expert Comment

by:roverm
ID: 9912373
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.
0
 
LVL 3

Expert Comment

by:patriziop
ID: 9912374
sorry for the typo --> set de default value to "x" or wahtever value diferent to a empty string
0
 
LVL 1

Author Comment

by:dba123
ID: 9912831
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
0
 
LVL 12

Expert Comment

by:roverm
ID: 9912971
>> 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.

D'Mzz!
RoverM
0
 
LVL 5

Expert Comment

by:TRUENEUTRAL
ID: 9913118
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

eg.

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
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9913403
Hi,

@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 asp.net 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">
<HTML>
      <HEAD>
            <title>cbnew</title>
            <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="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <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>
            </form>
      </body>
</HTML>


=================
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

#Region
    <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
        InitializeComponent()
    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
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:patriziop
ID: 9914082
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
0
 
LVL 3

Expert Comment

by:patriziop
ID: 9914191
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.
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9914953
Hi,

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>
            </form>


Best regards, Raisor
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9915033
Hi,

@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
0
 
LVL 12

Expert Comment

by:roverm
ID: 9920265
No prob!
dba123, any progress here?
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9920321
patriziop,

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
0
 
LVL 1

Author Comment

by:dba123
ID: 9925675
<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.
0
 
LVL 12

Expert Comment

by:roverm
ID: 9926555
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!
0
 

Accepted Solution

by:
YensidMod earned 0 total points
ID: 9945855
I have deleted all non technical comments.  Question has been PAQed and 500 points refunded.  If anyone wants to discussed this further, post here

http://www.experts-exchange.com/Community_Support/Q_20823741.html

YensidMod
Experts Exchange Moderator
0
 
LVL 5

Expert Comment

by:Netminder
ID: 9953950
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 http://www.experts-exchange.com/help.jsp#hs4 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: http://www.experts-exchange.com/Q_20827765.html (deleted by roverm request)
Raisor: http://www.experts-exchange.com/Q_20827767.html
patriziop: http://www.experts-exchange.com/Q_20827768.html
TRUENEUTRAL: http://www.experts-exchange.com/Q_20827770.html

Netminder
EE Admin
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now