4

I have a form that has many checkboxes (too many for it to make sense to use their own rules), and I need to use the jQuery Validation Plugin to make sure at least one of them is selected. They all have different names, so most of the solutions I've found so far by Googling don't work for me.

However, I came across this post, which I tweaked a bit to make this extension method:

// method for checking out checkboxes for the form validation
$.validator.methods.checkboxes_checked = function(value,element,param) {
   return ($('#signup #checkboxes input[type=checkbox]:checked').length > 0);
}

... which returns true or false depending if there are any of the checkboxes selected. I don't want to use the method from the above post verbatim, since that would require making separate rules for each checkbox, and as I have a lot of them (20+), that doesn't make much sense to me.

My only issue is that I don't know how to wire this into my validation call, since I don't have a "single" element on the page to tie it too (as in, all my other validation rules are tied to a specific single element, whereas my extension method above would be--in essence--tied to 20+ elements). Here's how my validation call looks now:

// validate the form
$('#signup').validate({
   rules: {
      'bedrooms': { required: true },
      'maxrent': { required: true },
      'term': { required: true },
      'movedate': { required: true },
      'firstname': { required: true, minlength: 2 },
      'lastname': { required: true, minlength: 1, maxlength: 1 },
      'email': { required: true, email: true },
      'day_telephone': { required: true, digits: true, minlength: 10, maxlength: 10 }
   },
   errorPlacement: function(error, element) { error.css('display','none'); },
   highlight: function(element, errorClass) { 
      $(element).fadeOut(function() { $(element).fadeIn(); });
      $('label[for='+$(element).attr('name')+']').css('color','red');
   },
   unhighlight: function(element, errorClass) { $('label[for='+$(element).attr('name')+']').css('color','black'); },
   onkeyup: false
});

I want, basically, for the form itself to check (using the jQuery Validation Plugin) if my extension method returns true before submitting. How can I add this in?

6 Answers 6

10

I don't know how your formular looks and where you want your error messages, but have you tried adding a custom validation method?

$.validator.addMethod("checkboxes", function(value, element) {
    return $('input[type=checkbox]:checked').length > 0;
}

And then adding it as a rule for just one of your checkboxes:

rules: {
    'idofacheckbox' : { checkboxes: true }
}

This one checkbox will then be valid if at least one checkbox is selected, or invalid when none are.

1
  • Ahh, that's what I needed to hear. I kept my method mentioned above and assigned it to one of my checkboxes ('random_checkbox': 'checkboxes_checked'), and it worked. I already know about the error placement issue. Don't know why I didn't try this before, but thanks for the suggestion!
    – neezer
    Nov 10, 2009 at 19:40
1

Michaelk's solution saved my life.

I just assigned checkbox_1 class to the checkboxes I want to validate. change the addMethod a bit.

$.validator.addMethod("checkbox_1", function(value, element) {
return $('.checkbox_1:checked').length > 0;

}

To group the error for all the checkboxes with the class assinged:

groups: {
   checkbox_1: "checbox1 checkbox2 checkbox3"

}

Apply a rule to the first checkbox as michalek

rules: {
'idofacheckbox' : { checkbox_1: true }

}

And that's it. works great and just one error appears for all the checkboxes being validated.

0

Use jQuery submit() function to prevent the form of being sent before being validated.

2
  • But that's not part of the Validation Plugin's flow; I want to incorporate this all into using the Validation plugin so I keep all the validation code centralized. Is there a way you know of that is within the scope of the validation plugin's capability and not outside of it?
    – neezer
    Nov 10, 2009 at 19:24
  • actually, there is. Add event: "submit" to the parameters of the validate function.
    – yoda
    Nov 10, 2009 at 22:57
0
$('#myform').submit(
    function(){
        //  check the checkboxes
        if (okay_to_submit)
            forms['myform'].submit();
    }
);
1
  • Again, this doesn't use the Validation plugin. I know I can do it using straight jQuery, but I want this method to be part of the Validation plugin call.
    – neezer
    Nov 10, 2009 at 19:28
0
$.validator.addMethod("checkboxes", function(value, element) {
  return $('input[type=checkbox]:checked').length > 0;
}

Any code that uses a generic jQuery expression is not guaranteed to work. The parameter 'element' must somehow be used otherwise the whole page is queried for any/all checkboxes.

I believe logic is required to identify the other elements in the group based on the element provided.

Perhaps the best option would be if the 'group' property was dynamically created and then passed to the validator method. Eg, use classes on your inputs like "atLeastOne-checkboxes group_1" and the validator callback must be function(value, element, (Array) elements_in_group) {}

0

I had a use case where the checkboxes had different name attr, no ID and no class and I could not alter the markup. My rules were:

...
rules: {
  'preferred_contact_method[Email]': {
    checkone: true,
  },
  'preferred_contact_method[Phone]': {
    checkone: true,
  },
  'preferred_contact_method[Mail]': {
    checkone: true,
  },
},
...

and then my custom validator went up the dom tree to find the wrapper of the checkboxes and simply returned if any were checked.

$.validator.addMethod('checkone', function(value, element) {
  const boxes = $(element).closest('.js-webform-checkboxes');
  return boxes.find('input:checked').length;
}, 'Please select one.');

Also, used the groups option to only show the error message once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.