VB.NET - Validation to choose at least one in radiobuttons and checkedlistbox

Asked By onay omas on 17-Aug-11 10:52 PM
Hi,
how to make validation for user to check at least one from radiobuttons(in groupbox or not) and also in a
checkedlistbox.
If none of the radiobuttons choosen, then give message.
Same as in checkedlistbox.

Thank you
Web Star replied to onay omas on 17-Aug-11 11:27 PM
You can put two asp:RequiredFieldValidator control one for radiobutton list and one for checkboxlist
here is example for radiobuttonlist

  1. <asp:RadioButtonList   
  2.       ID="RadioButtonList1"  
  3.       runat="server"  
  4.       RepeatColumns="3"  
  5.       BackColor="DodgerBlue"  
  6.       ForeColor="AliceBlue"  
  7.       BorderColor="DarkBlue"  
  8.       BorderWidth="2"  
  9.       >  
  10.       <asp:ListItem>CheckBoxList</asp:ListItem>  
  11.       <asp:ListItem>TreeView</asp:ListItem>  
  12.       <asp:ListItem>Button</asp:ListItem>  
  13.       <asp:ListItem>SqlDataSource</asp:ListItem>  
  14.       <asp:ListItem>GridView</asp:ListItem>  
  15.       <asp:ListItem>Calendar</asp:ListItem>  
  16.       <asp:ListItem>BulletedList</asp:ListItem>  
  17.     </asp:RadioButtonList>  
  18.     <asp:RequiredFieldValidator   
  19.       ID="ReqiredFieldValidator1"  
  20.       runat="server"  
  21.       ControlToValidate="RadioButtonList1"  
  22.       ErrorMessage="Select your favorite!"  
  23.       >  
  24.     </asp:RequiredFieldValidator>
IN same way you can put another for checkboxlist control
Also you can put client side validation in javascript function for both control must be selected at least one.
http://weblogs.asp.net/mikebosch/archive/2007/10/11/client-side-validators-for-checkbox-and-checkboxlist.aspx
eg. 
TSN ... replied to onay omas on 17-Aug-11 11:54 PM
hi..

Javascript radio buttons validation
Suppose you have a radio button in your form and you want the useres to select atleast one option. You can do this by using javascript radio button validation script.See the example below.

Your Gender: Male Female


Put the following piece of javascript in your function function ValidateForm(form)
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
  alert ( "Please choose your Gender: Male or Female" );
  return false;
}



Try the following code:

<script LANGUAGE="JavaScript">
<!--
function ValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) ) { alert ( "Please choose your Gender: Male or Female" ); return false; }
if (ErrorText= "") { form.submit() }
}
-->
</script>
<br><form name="feedback" action="mailto:webgimmicks@email.com" method=post>
Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>

Validating checkboxes using javascript
Suppose you have a checkbox in your form and you want the users to select that before submiting the form. You can use Javascript checkbox validation script. See the example below.

Do you agree to the Terms and Conditions? Yes


Put the following Javascript in your function function ValidateForm(form)

if ( form.terms.checked == false )
 {
   alert ( "Please check the Terms & Conditions box." );
    return false;
}



Try the following code:

<script LANGUAGE="JavaScript">
<!--
function ValidateForm(form){
ErrorText= "";
if ( form.terms.checked == false ) { alert ( "Please check the Terms & Conditions box." ); return false; }
if (ErrorText= "") { form.submit() }
}
-->
</script>
<br><form name="feedback" action="mailto:webgimmicks@email.com" method=post>
Your Gender: <input type="checkbox" name="terms" value="Yes"> Yes
<input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>



hope this helps you..
Jitendra Faye replied to onay omas on 17-Aug-11 11:56 PM

Folllow these steps-

Step1: Take CustomValidator like this-

<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="Validate" ControlToValidate="CheckBoxList" runat="server">Required.</asp:CustomValidator>


Step2: Use this client side function to validate CheckBoxList.



function Validate(source, arguments) {

var list = document.getElementById('<%=CheckBoxList.ClientID %>').rows;

var counter = 0;

for (i = 0; i < list.length; i++) {

if (list[i].cells[0].childNodes[0].type == "checkbox") {

if (!list[i].cells[0].childNodes[0].checked) {

counter++;

}

}

}

if (counter < list.length)

arguments.IsValid = true;

else

arguments.IsValid = false;

}

Hope this will help you.

Asked By onay omas on 18-Aug-11 12:15 AM
Hi,

Your code seems works for checkedlistbox.
Million thanks!
Still search for radiobutton's validation

For all those replied my questions,
i really appreciated all your replies.

p/s: Sorry im not stated that im using vb.net and windows app.
For radio button - Anoop S replied to onay omas on 18-Aug-11 12:20 AM

I think this will help for radio button

function ValidateAnswerRadio()

{

   var list = document.getElementById('<%=RadioButtons.ClientID %>').childNodes;

   for(i = 0; i <  list.length; i++)

      if(list[i].type == "radio")

           if(list[i].checked) return true;

   return false;

}

<asp:RadioButtonList runat="server" ID="RadioButtons">

           <asp:ListItem Text="option1"></asp:ListItem>

           <asp:ListItem Text="option2"></asp:ListItem>

       </asp:RadioButtonList>

<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="ValidateRadio" runat="server">Required.</asp:CustomValidator>

Riley K replied to onay omas on 18-Aug-11 12:27 AM

The simplest way is using a RadioButtonList and a RequiredFieldValidator.

    
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem>north</asp:ListItem>
    <asp:ListItem>west</asp:ListItem>
  </asp:RadioButtonList>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
    ControlToValidate="RadioButtonList1" ErrorMessage="RequiredFieldValidator">
  </asp:RequiredFieldValidator>

 2. Without RadioButtonList and if you want a group radiobutton insteads, you can also implement it by CustomValidator.


<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{  
  if(document.getElementById("<%= RadioButton1.ClientID %>").checked || document.getElementById("<%= RadioButton2.ClientID %>").checked)
  {
    args.IsValid = true;
  }
  else
  {
    args.IsValid = false;
  }
   
}
//-->
</script>
<body>
  <form id="form1" runat="server">
  <div>  
  <asp:RadioButton ID="RadioButton1" runat="server" GroupName="location" Text="north" />
  <asp:RadioButton ID="RadioButton2" runat="server" GroupName="location" Text="west" />
  <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
  <asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
  </div>
  </form>
</body>
 
   
 
  protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
  {
    args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    if (Page.IsValid)
    {
      //validate is successful.
    }
  }
Here is the way to  client side validation for checkboxlist control.


<head runat="server">
  <title>CheckBox list validation</title>
  <script type="text/javascript">
  
    function validateChk() {
      var found = false;
      var validated = false;
      var id = document.getElementById("<%=chkList.ClientID %>").id;
      var elements = document.forms[0].elements;
      for (i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox" && elements[i].id.indexOf(id) > -1) {
          found = true;
          if (elements[i].checked) {
            validated = true;
            break;
          }
        }
      }
      if (found && validated)
        return true;
      else {
        alert('Please Select atleast one item check box list');
        return false;
      }
  
    }
  
  
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:CheckBoxList ID="chkList" runat="server">
      <asp:ListItem>Diploma</asp:ListItem>
      <asp:ListItem>BE</asp:ListItem>
      <asp:ListItem>MTech</asp:ListItem>
      <asp:ListItem>MBA</asp:ListItem>
    </asp:CheckBoxList>
    <br />
    <asp:Button ID="btnSubmit" runat="server" OnClientClick="return validateChk();" Text="Validate" />
  </div>
  </form>
</body>

Cheers
aneesa replied to onay omas on 18-Aug-11 12:49 AM

int select = 0;

for (int i = 0; i < chkGrade.Items.Count; i++) //chkGrade is the checkboxlist

{

if (chkGrade.Items[i].Selected == true)

{

select += 1;

}

}

if (select == 0)

{

//give message here

}

////////////////////////////////////////

 

int select2 = 0;

for (int i = 0; i < rdbl.Items.Count; i++) //rdbl is the radiobuttonlist

{

if (rdbl.Items[i].Selected == true)

{

select2 += 1;

}

}

if (select2 == 0)

{

//give message here

}

dipa ahuja replied to onay omas on 18-Aug-11 04:20 AM
Untitled document
<script type="text/javascript">
 
 function checkSelection() {
     var listItemArray = document.getElementsByName('<%= RadioButtonList1.ClientID %>');
     
    var isItemChecked = false;
     
    //Radio check
     for (var i = 0; i < listItemArray.length; i++) {
       var listItem = listItemArray[i];
       if (listItem.checked) {
         isItemChecked = true;
       }
     }
        if (isItemChecked == false) {
       alert('Check atleast one item!');
       return false;
     }
     return true;
   
  }
</script>
 
<asp:RadioButtonList ID="RadioButtonList2" runat="server"
   AutoPostBack="True">
   <asp:ListItem>Yes</asp:ListItem>
   <asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
 
â–ºCheckbox Validation
 
 <script type="text/javascript">
   var atLeast = 1
   function Validate() {
   var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");
   var checkbox = CHK.getElementsByTagName("input");
   var label = CHK.getElementsByTagName("label");
   var counter = 0;
   //validation to check atleast one item is selected
   for (var i = 0; i < checkbox.length; i++) {
     var checkitem = checkbox[i];
     if (checkitem.checked) {
     //Give the selected Checkbox value
     alert(label[i].innerHTML);
     counter++;
     }
   }
   if (atLeast > counter) {
     alert("Please select atleast " + atLeast + " item(s)");
     return false;
   }
   return true;
   }
   </script>
<asp:Button ID="Button3" runat="server" Text="Button" OnClientClick="return Validate();" />
 <asp:CheckBoxList AutoPostBack="true" ID="CheckBoxList1" runat="server">
   <asp:ListItem>ASP./net</asp:ListItem>
   <asp:ListItem>C#</asp:ListItem>
 </asp:CheckBoxList>
 
Radhika roy replied to Jitendra Faye on 18-Aug-11 09:45 AM



Try this working code-


<
script type = "text/javascript">
function
 GetSelectedItem()

{

   var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");

   var checkbox = CHK.getElementsByTagName("input");

   var flag = "false";

   for (var i=0;i<checkbox.length;i++)

   {

     if (checkbox[i].checked)

     {

      flag="true";       
     }

  }


   if(flag="true")
    { 
        return true;
      }
   else
    {
        alert("select any value");
    }
   return false;

}

</script> 

<asp:Button ID="Button2" runat="server" Text="SelectedItem" OnClientClick

 = "return GetSelectedItem()" />

Hope this will help you.