对克隆元素的Jquery验证

时间:2013-03-08 13:39:50

标签: javascript jquery validation

我正在使用以下JQuery验证:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

我有以下元素:

<div class="form-item">
  <label for="Reference_name" class="required">Name: <span class="required">*</span></label>                        
   <input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">                                        
</div>

我克隆了元素,但验证仅出现在第一个元素上。我希望它也能对第二个进行验证并显示错误消息标签。

请有人帮忙解决这个问题。

2 个答案:

答案 0 :(得分:0)

元素必须是唯一的

<label for="Reference_name" class="required">Name:<span class="required">*</span></label>            
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />

档案Js

$(document).ready(function() {
 validate_form();
});     


function validate_form() {
    $("#id_of_your_form").validate({
    rules: {
        'Reference_name': {
            required:true,
            minlength: 2,                
            }
        },
    },
    messages: {
        'Reference_name': {
            required:"Your name is required",
            minLength:'Your name is too short'
        },           
    }

});
}

如果你想比较两个字段 http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other

答案 1 :(得分:0)

将验证函数放在这样的全局变量中:

var validate_form_function = function(){
                if($(".app-form").length > 0){
                  $('.app-form').validate({
                    rules: {
                            comment_message: {
                                required: true,
                                minlength: 2
                            }
                    },

                    messages: {
                            comment_message: {
                                required: "Your message",
                                minlength: "Your message"
                            }
                    }
                  });
                }
            };

然后使用如下函数重新验证克隆的表单: validate_form_function();