« back

Checkbox Dependency with JQuery Validation

21 Sep 2012

Lessons learned from a first go at form validation.

This week I was given the task of creating a form, validating it and hooking it up to a database. I would like to share some cool things I learned along the way and also help you speed up your process if you are having the same kind of problem I was.

In my form, there was a question which had you select a radio button for the answer. If the radio button answer was yes, you needed to then select at least one option from a list of checkboxes. I needed my validation to enforce this. Using the JQuery Validation plugin, there was really no way to do this straight out of the box. Before I show you the amazing solution, let me talk about some things I tried that did not work.

I found some ideas about where to head but they usually were relying on the fact that name field in the html was always the same. I needed them to be different for my database.

The first thing that did not work. Using required( dependency-expression ). When using this it will require every checkbox to be checked if the radio button input is yes. This is certainly not the outcome we were looking for.

Then, I decided to write a custom method with the .addMethod method. I added a class onto each checkbox input (class="former-church") and I did this...

1     $.validator.addMethod('formerchurch', function (value) {
2       return $('.former-church:checked').size() > 0;
3     }, 'Please select at least one former church.');

Based off of some other posts I saw, I tried in my rules, to dynamically get the value from the form, like this...

1     Answer_03a_former_church_catholic: {
2     	  formerchurch: ($("input[name=Answer_03_attend_prior_church]:checked").val() == "yes" )
3       },

The problem with this is that the rules are set when the page loads and the answer is not known yet so it will always require you to fill in checkboxes. The solution is to set the custom rule to be true so it looks like this...

1     Answer_03a_former_church_catholic: {
2     	  formerchurch: true
3       },

and then to place the responsibility of getting the value on the function that will run after the form is submitted.

$.validator.addMethod('formerchurch', function (value) { if ($("input[name=Answer_03_attend_prior_church]:checked").val() == "yes" ) { return $('.former-church:checked').size() > 0; } else { return true; } }, 'Please select at least one previous church type.');


comments powered by Disqus