Sometimes we need to validate an array of input elements: For example –

<form name="checkform" class="form-control" id="checkform" method="post" action="">
	<select name="field_name&#91;&#93;" 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&#91;&#93;" 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 –

<script type="text/javascript">
	$().ready(function() {
		$("#checkform").validate({
			rules: {
				"field_name[]": "required"
			},
			messages: {
				"field_name[]": "Please select field option",
			}
		});
	});
</script>

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:

// 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(); }, [/code]


4 Comments

Ankit Doshi · June 4, 2019 at 5:02 pm

This solution worked perfectly fine. It is exactly what I was looking for. 🙂
Thanks Shushant.

haresh chauhan · May 1, 2020 at 6:24 pm

its working only below field
not working at Saperat field

Saul Ayala · November 13, 2020 at 8:30 pm

Oh man, you save my day! your are the shit! 👍👍👍👍👍

Leave a Reply

Avatar placeholder

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