0

I have two input checkboxes as below:

<input type="checkbox" value="1" name="items[test1]" id="items_test1">
<input type="checkbox" value="1" name="items[test2]" id="items_test2">

I want atleast one of them to be checked. For that I added jquery validate plugin code as below:

 $.validator.addMethod("checkTest", function(value) {
    return false; // return false just to check whether it triggers error
}, 'Please check atleast one');

 $(document).ready(function() {
     $("form").validate({
         groups: {
            checkTest: 'items[test1] items[test2]'
         },
         errorPlacement: function(error, element) {
              console.log(error);
     });
 });

This check is nevered triggered. What am I doing wrong?

sonam
  • 3,720
  • 12
  • 45
  • 66

2 Answers2

0

I know you want to do this using validate plugin, but just in case if you want to go manually then you can use this method.

HTML

<form>
    Checkbox 1: <input type="checkbox" value="1" name="items[test1]" id="items_test1">
    <br>
    Checkbox 2: <input type="checkbox" value="1" name="items[test2]" id="items_test2">

    <br>
    <input type='submit' value='Submit' />
</form>

JS

$(document).ready(function() {
    $(document).on('submit', 'form', function() {
        if($('#items_test1').is(':checked') || $('#items_test2').is(':checked')) {
             alert('done. valid form submission.');   
        } else {
             alert('invalid form submission, check atleast one checkbox.');   
        }
        return false; 
    });
})

You can find this on jsfiddle here.

user1995997
  • 581
  • 2
  • 8
  • 19
0

You have set up the group, but you haven't added any validation rules to your checkboxes. I would use the require_from_group method found in the additional methods file of the plugin. In document ready:

// add a class to the checkboxes in the group, here I have added to all
$('[type=checkbox]').addClass('test_checkboxes');

// set up a rule for the class
$.validator.addClassRules("test_checkboxes", {
    require_from_group: [1, ".test_checkboxes"]
});

$("form").validate({
    groups: {
        checkTest: 'items[test1] items[test2]'
    }
});

fiddle here

politus
  • 5,996
  • 1
  • 33
  • 42
  • I know sometimes documentation for this plugin is sparse, but is there anything written for `require_from_group` you could link to? – Sparky Jan 29 '13 at 08:46
  • for documentation on require_from_group there is an original post on this method on SO here http://stackoverflow.com/q/1300994/678338 – politus Jan 29 '13 at 09:06
  • sonam this is a new question eg 'how to specify a custom error messages when using validate plugin groups option' – politus Jan 29 '13 at 09:08
  • 2
    @sonam, [see this jsFiddle for how to use a the custom error message for `require_from_group` option: jsfiddle.net/LWwxL/1/](http://jsfiddle.net/LWwxL/1/) – Sparky Jan 29 '13 at 15:32