jquery validation dynamic fields validate code example
Example: jquery validation dynamic fields
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1;
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
event.preventDefault();
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
$("#addInput").on('click', addInput);
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!