3

How to validate all select inputs when this is a dynamic array? Like this:

I used laravel 4.2 blade

<tr><td> {{ Form::select('items[]', $items,  null, array('class'=>'form-control items', 'required')) }} </td></tr>

and this is form validation code

if ($('.val-form').length > 0) {
    $('.val-form').validate();
}

then i create a button to generate new select inputs

$(document).on('click', '.add-item', function (e) {
        var row = $(this).closest('tr').prev('tr').clone();
        row.find('input').val('');
        $(this).closest('tr').before(row);
        e.preventDefault();
    });

after i click add button the form only validate dom inputs and new added inputs not validated

enter image description here

ALL GENERATED INPUTS CREATED WITH THE SAME NAME "items[]"

and if i forget to put any items values in the form i got items array on server side with empty values

'items' => 
array (size=2)
  0 => string '42' (length=2)
  1 => string '' (length=0) // this empty value cause i forget to fill all inputs
Maged Hamid
  • 952
  • 1
  • 9
  • 18

1 Answers1

-1

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

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();
}

This will validate array input fields with the same name like "items[]" I found this solution on this link

Maged Hamid
  • 952
  • 1
  • 9
  • 18