How to validate a form with multiple checkboxes to have atleast one checked

前端 未结 11 789
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 23:40

I\'m trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be sub

相关标签:
11条回答
  • 2020-11-30 23:59

    This script below should put you on the right track perhaps?

    You can keep this html the same (though I changed the method to POST):

    <form method="POST" id="subscribeForm">
        <fieldset id="cbgroup">
            <div><input name="list" id="list0" type="checkbox"  value="newsletter0" >zero</div>
            <div><input name="list" id="list1" type="checkbox"  value="newsletter1" >one</div>
            <div><input name="list" id="list2" type="checkbox"  value="newsletter2" >two</div>
        </fieldset>
        <input name="submit" type="submit"  value="submit">
    </form>
    

    and this javascript validates

    function onSubmit() 
    { 
        var fields = $("input[name='list']").serializeArray(); 
        if (fields.length === 0) 
        { 
            alert('nothing selected'); 
            // cancel submit
            return false;
        } 
        else 
        { 
            alert(fields.length + " items selected"); 
        }
    }
    
    // register event on form, not submit button
    $('#subscribeForm').submit(onSubmit)
    

    and you can find a working example of it here

    UPDATE (Oct 2012)
    Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

    UPDATE (May 2013)
    Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

    UPDATE (June 2016)
    Changes == to ===

    0 讨论(0)
  • 2020-12-01 00:04

    I had a slighlty different scenario. My checkboxes were created in dynamic and they were not of same group. But atleast any one of them had to be checked. My approach (never say this is perfect), I created a genric validator for all of them:

    jQuery.validator.addMethod("validatorName", function(value, element) {
        if (($('input:checkbox[name=chkBox1]:checked').val() == "Val1") ||
            ($('input:checkbox[name=chkBox2]:checked').val() == "Val2") ||
            ($('input:checkbox[name=chkBox3]:checked').val() == "Val3")) 
        {   
            return true;
        }
        else
        {
            return false;
        }       
    }, "Please Select any one value");
    

    Now I had to associate each of the chkbox to this one single validator.

    Again I had to trigger the validation when any of the checkboxes were clicked triggering the validator.

    $('#piRequest input:checkbox[name=chkBox1]').click(function(e){
        $("#myform").valid();
    });
    
    0 讨论(0)
  • 2020-12-01 00:05

    The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:

    $.validator.addMethod('cb_selectone', function(value,element){
        if(element.length>0){
            for(var i=0;i<element.length;i++){
                if($(element[i]).val('checked')) return true;
            }
            return false;
        }
        return false;
    }, 'Please select at least one option');
    
    0 讨论(0)
  • 2020-12-01 00:05
    if (
      document.forms["form"]["mon"].checked==false &&
      document.forms["form"]["tues"].checked==false &&
      document.forms["form"]["wed"].checked==false &&
      document.forms["form"]["thrs"].checked==false &&
      document.forms["form"]["fri"].checked==false
    ) {
      alert("Select at least One Day into Five Days");
      return false; 
    }
    
    0 讨论(0)
  • 2020-12-01 00:05

    Good example without custom validate methods, but with metadata plugin and some extra html.

    Demo from Jquery.Validate plugin author

    0 讨论(0)
  • 2020-12-01 00:05

    I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.

    // param: reqNum number of checkboxes to select
    $.fn.checkboxValidate = function(reqNum){
        var fields = this.serializeArray();
        return (fields.length < reqNum) ? 'invalid' : 'valid';
    }
    

    then you can pass this function to check multiple group of checkboxes with multiple rules.

    // helper function to create error
    function err(msg){
        alert("Please select a " + msg + " preference.");
    }
    
    $('#reg').submit(function(e){
        //needs at lease 2 checkboxes to be selected
        if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
            err("Region and Music");
        } 
    });
    
    0 讨论(0)
提交回复
热议问题