【问题标题】:How validate JQuery clone form如何验证 JQuery 克隆表单
【发布时间】:2026-02-18 06:10:01
【问题描述】:

在我的工作中,我曾经回答过这个问题:

JQuery clone form and increment

如何验证使用 JQuery Validation 克隆表单?

我尝试了以下方法,但没有成功:

    $(document).ready(function () {
    $(function () {
        var template = $('#attendees .attendee:first').clone(),
            attendeesCount = 1;
        var addAttendee = function () {
            attendeesCount++;
            var nativeTemplate = template.clone();
            var attendee = nativeTemplate.find(':input').each(function () {
                var newId = this.id.substring(0, this.id.length - 1) + attendeesCount;
                $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
                this.name = this.id = newId; // update id and name (assume the same)
            }).end() // back to .attendee
                .attr('id', 'att' + attendeesCount) // update attendee id
                .prependTo('#attendees') // add to container
                .validate(
                    // rules
                );
        };
        $('.add').click(addAttendee); // attach event
    });
});

【问题讨论】:

    标签: jquery forms validation clone increment


    【解决方案1】:

    在再次调用 validate 之前,您需要删除附加到克隆表单的旧验证器数据。

    所以你的代码的结尾应该是这样的:

               .prependTo('#attendees') // add to container
               .removeData('validator') //get rid of cloned validator
                .validate(
                    // rules
                );
    

    【讨论】:

      【解决方案2】:

      试试 сlone(true),它会将事件处理程序附加到克隆对象,它可能会有所帮助。

      【讨论】:

        【解决方案3】:

        我使用了这种方法:

        //Clone the form
        var clonedForm = $('.original-form').clone(true);
        
        //Get original form & validator
        var originalform = $('.original-form').find('form');
        var originalValidator = originalform.data('validator');
        
        //Set validator to cloned form in popup
        originalValidator.currentForm = clonedForm;
        
        //Re-Set the validator to the cloned form
        clonedForm.data('validator', originalValidator);
        
        //Now you can validate the clonedForm by calling "valid()".
        $(clonedForm).valid()
        

        希望这会有所帮助。

        【讨论】: