I'm trying to do a validation for a dynamic field with validate, but it only validates once. The dynamically added fields are not being validated below:
$(document).ready(function() {
$(".data").mask("99/99/9999");
var i = 1;
$('a#adicionar').click(function() {
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td>Inicio:</td><td><input name="inicio[]" id="inicio' + i + '" type="text" value="" class="form-control data" /></td><td>Término:</td><td><input name="termino[]" id="termino' + i + '"type="text" value="" class="form-control data" /></td><td><a name="remove" id="' + i + '" class="btn btn-danger btn_remove"><i class="fa fa-times-circle">-</i></a></td></tr>');
$(".data").mask("99/99/9999");
$("#inicio" + i + "").focus();
});
$(document).on('click', 'a.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$("#teste").validate({
rules: {
'inicio[]': {
required: true,
date: true
},
'termino[]': {
required: true,
date: true
}
},
messages: {
'inicio[]': "* Informe uma data",
'termino[]': "* Informe uma data",
},
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error')
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
},
//errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script><linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script><formid="teste">
<div class="col-sm-12">
<table class="table" width="100%" id="dynamic_field">
<tr>
<td>Inicio:</td>
<td>
<input name="inicio[]" id="inicio" type="text" value="" class="form-control data" />
</td>
<td>Término:</td>
<td>
<input name="termino[]" id="termino" type="text" value="" class="form-control data" />
</td>
<td></td>
</tr>
</table>
<a id="adicionar" class="btn btn-success" title="Adicionar data de início e término"><i class="fa fa-plus-circle">+</i></a>
</div>
<button type="submit" id="btn_passo2" class="btn btn-primary next-step">Salvar</button>
</form>
I've also put jbfiddle in tbm for better understanding link
Thanks in advance for any help.