2

I would like to store the checkbox value in an array, however, i can not use the validate rules since the name is selectList[] instead of selectList. I tried id but it seems the rule only bind to the name.

html:

<input id='sendList' type='checkbox' name='selectList[]' value='$set[ListID]'>

js rule:

  $("#selectList").validate( {
      rules: {
          selectList[]: {
              required: true,
              minlength: 1
          }
       }
   })

});

Thank you

user782104
  • 13,233
  • 55
  • 172
  • 312

2 Answers2

1

Problem is that the readymade jquery.validate.js only validates the first element of category[]. So, we need to modify it a little bit.

In jquery.validate.js, find a function named checkForm, we have to modify it as below:

checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
} else {
this.check( elements[i] );
}
}
return this.valid();
},
Minhaj Mimo
  • 826
  • 9
  • 18
-1

Why not wrap selectList[] inside quotes:

$("#selectList").validate({
    rules: {
        'selectList[]': {
            required: true,
            minlength: 1
        }
    }
});

In initializing Javascript object property names, they can be an identifier (the way you tried), a number or a string.

Working code: http://jsfiddle.net/rMgLG/

sransara
  • 3,454
  • 2
  • 19
  • 21
  • 3
    Actually this is a non working answer. jQuery validate doesn't allow validation for multiple fields with the same name, so in the above answeronlthe first field with name `selectList[]` would be validated which doesn't help much if you trying to post an array of fields... – jtheman Mar 12 '13 at 14:22