验证动态添加的字段

时间:2017-07-11 09:42:44

标签: jquery validation

单击添加按钮时,会动态添加新输入。但是,在提交表单时,只验证第一个输入字段。如何验证动态添加的输入?

以下是我的代码:

<body>
    <section class="container">
        <div class="majors">
            <h1>Department</h1>
        </div>
        <form class="hform" id="selectForm" action="/action_page.php">
            <select name="Department">
                <option value="Sociology" selected>Sociology</option>
                <option value="Science">Science</option>
                <option value="Humanities">Humanities</option>
                <option value="Linguistics">Linguistics</option>
            </select>

            <div class="sbutton">
                <input type="button" id="submit_form" value="submit" />
            </div>
            <button class="delete" type="button" value="delete">Delete</button>
        </form>
    </section>

    <section class="container">
        <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
            <fieldset>
                <div class="form-copy-wrap">
                    <input class="checkbox" type="checkbox" />
                    <p>
                        <label for="aname">Name</label>
                        <input name="name[]" minlength="5" type="text" required/>
                    </p>
                    <p>
                        <label for="aemail">Email</label>
                        <input name="email[]" type="email" required/>
                    </p>
                    <p>
                        <label for="aage">Age</label>
                        <input name="age[]" type="number" required/>
                    </p>
                </div>
                <div class="input_fields_wrap">
                    <div class="addButton">
                        <button type="button" value="add">Add</button>
                    </div>
                </div>
            </fieldset>
        </form>
    </section>
    <script>
        $("#submit_form").on('click', function (e) {
            e.preventDefault();
            $("form#commentForm").submit();
            $(".form-copy-wrap").submit();
        });
        $("form#commentForm").validate({
            rules: {
                name: "required",
                email: {
                    required: true,
                    email: true,
                }
            },
            messages: {
                name: "Please specify your name",
                email: {
                    required: "We need your email address to contact you",
                    email: "Your email address must be in the format of name@domain.com"

                }
            }
        });
    </script>

    <script>
        $(document).ready(function () {
            var max_fields = 10;
            var counter = 0;

            $('.addButton').on('click', function () {
                counter++;
                if (counter >= max_fields) {
                    console.log('You have reached a max limit fields')
                    return;
                }
                var copy = $('.form-copy-wrap').first().clone();

                $("#commentForm fieldset").append(copy);
            });

            $('.delete').on('click', function () {
                $('input:checkbox').each(function () {
                    if ($(this).is(':checked')) {
                        $(this).closest('.form-copy-wrap').remove();

                    }
                });
            });
        });
    </script>
</body>

2 个答案:

答案 0 :(得分:1)

您可以在表单提交之前验证表单,并为动态添加的输入实现验证。使用jquery $.each为每个人添加规则,并实现如下的验证。

&#13;
&#13;
$(document).ready(function() {          
        var inputCount = 1; // used to increment the name for the inputs

        function addInput() {
            $('.form-copy-wrap').append($('<p>New Input: <input class="required" name="name'+inputCount+'" /></p>'));
            inputCount++;
        }

        $('form.commentForm').on('submit', function(event) {
            // adding rules for inputs with class 'required'
            $('#inputs input.required').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("valid");
            } else {
                // prevent default submit action
                event.preventDefault();
                console.log("not valid");
            }
        })

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

        // initialize the validator
        $('form.commentForm').validate();

   });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form class="commentForm" method="get" action="" style="float:left">
    <div>
         <div class="form-copy-wrap">
            <input class="checkbox" type="checkbox" />
            <p>
                <label for="aname">Name</label>
                <input name="name[]" minlength="5" type="text" required/>
            </p>
            <p>
                <label for="aemail">Email</label>
                <input name="email[]" type="email" required/>
            </p>
            <p>
                <label for="aage">Age</label>
                <input name="age[]" type="number" required/>
            </p>
         </div>

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

    </div>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

请用这个替换点击事件

 $('.addButton').on('click', function () {
    counter++;
    if (counter >= max_fields) {
       console.log('You have reached a max limit fields')
       return;
    }
    var copy = $('.form-copy-wrap').first().clone();

    $("#commentForm fieldset").append(copy);

    var form = $("#commentForm");
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(document);
});