Form validation that contains arrays from checkboxes and radio buttons with jQuery

I’m using the jQuery plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation. The plugin is greate. I did run into a problem with arrays. Say your form has a group of checkboxes or radio buttons and their names are checkbox or radio. To have them be in the same group, their names have to be the same and to process it using PHP as post variables you have to throw them in arrays. So in the form their names will be checkbox[] or radio[].

In your validation you probably have something like

rules: {
  checkbox: { required: true },
  radio: { required: true }
}

The element name no longer matches because in your form they are checkbox[] and radio[] while in your javascript they are checkbox and radio. To solve this, use quotes and add the []. So here’s a quick example.


$(document).ready(function() {
  $('#form1').validate({
    rules: {
      "checkbox[]": { required: true },
      "radio[]: { required: true }
    }
  });
});


<form id="form1">
<input name="checkbox[]" type="checkbox" value="checkbox1" /> checkbox 1
<input name="checkbox[]" type="checkbox" value="checkbox2" /> checkbox 2

<input name="radio[]" type="radio" value="radio1" checked="checked" />radio  1
<input name="radio[]" type="radio" value="radio2" />radio  2
</form>

The radio button is an overkill since you normally have 1 checked by default unless you forget. The plugin is great so if you haven’t checked it out, I highly recommend it.

One thought on “Form validation that contains arrays from checkboxes and radio buttons with jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s