Validate Dynamically Added Input 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; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                        required: true

            // prevent default submit action         

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
            } else {
                console.log("does not validate");

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator



And the html form part:

<form class="commentForm" method="get" action="">

        <p id="inputs">    
            <input class="comment" name="name0" />

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />


Good luck! Please approve answer if it suits you!

Leave a Comment