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

I’m using the jQuery plugin from 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() {
    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

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.

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *