asp.netcheckboxjquery-validatevalidation

Select at least one checkbox out of 3 required field validator


I am trying to make my code to put required field validator so at least one checkbox will be selected out of three.

This is my code:

<div class="left marginT5 marginR10">
 <input type="checkbox" id="chk1" value="option1" runat="server" class="styled" /> Choice1
 </div>
 <div class="left marginT5 marginR10">
<input type="checkbox" id="chk2" value="option2" runat="server" class="styled" /> Choice2
 </div>
 <div class="left marginT5 marginR10">
 <input type="checkbox" id="chk3" value="option3" runat="server" class="styled" /> Choice3
 </div>

I know I can use checkboxlist but because of design issues I can only use single checkbox controls. How can I "force" the user to select at least one checkbox?


Solution

  • You could try and use a Custom Validator. This should get you started:

    aspx

    <asp:CustomValidator ID="CustomValidator1" runat="server" 
        EnableClientScript="true"
        ErrorMessage="Please choose at least one"
        ClientValidationFunction="ValidateRadioButtons">
    </asp:CustomValidator> 
    

    javascript/jQuery

    function ValidateRadioButtons(source, args) {
      var options = $('.styled');
      for (var i = 0; i < options.length; i++) {
        if (options[i].checked) {
          args.IsValid = true;
          return false;
        }
      }
      args.IsValid = false;
    } 
    

    Custom Validator

    You should have server side validation too, just in case javascript is disabled.