Javascript jQuery
JQUERY: VALIDATE MULTIPLE FIELDS WITH THE SAME NAME
Sometimes we need to validate an array of input elements: For example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<form name="checkform" class="form-control" id="checkform" method="post" action=""> <select name="field_name[]" id="field_1"> <option value="">Select any</option> <option value="1">abc</option> <option value="2">abc</option> <option value="3">abc</option> <option value="4">abc</option> </select> <select name="field_name[]" id="field_2"> <option value="">Select any</option> <option value="5">xyz</option> <option value="6">xyz</option> <option value="7">xyz</option> <option value="8">xyz</option> </select> <input class="submit" value="Submit" type="submit"> </form> |
Now we will use jquery validation plugin jquery.validate.js for validating the form. The condition will be that user will have to choose field_name from each dropdown. The script for validation will be as below –
1 2 3 4 5 6 7 8 9 10 11 |
<script type="text/javascript"> $().ready(function() { $("#checkform").validate({ rules: { "field_name[]": "required" }, messages: { "field_name[]": "Please select field option", } }); });> |
Now the problem is that the jquery.validate.js only validates the first element of field_name[]. So, we need to modify it a little bit.
In jquery.validate.js, we can find a function named checkForm,
just comment out the org code
we have to modify it as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// checkForm: function() { // this.prepareForm(); // for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { // this.check( elements[i] ); // } // return this.valid(); // }, 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(); }, |
0 Comments
Share