简体   繁体   English

Jquery验证 - 向输入元素添加规则时出错?

[英]Jquery validation - Error on adding rules to input element?

I am trying to implement Jquery validation with http://docs.jquery.com/Plugins/Validation : 我正在尝试使用http://docs.jquery.com/Plugins/Validation实现Jquery验证:

My design plan: 我的设计方案:

  • My input element: 我的输入元素:

     <form action="submit.php" id="form_id"> <input type="text" class="val-req" id="my_input" name="myval" /> <input type="button" onclick="validate_form('form_id', function() { $('#form_id').submit(); })" /> <span id="val-msg" class="my_input"></span> </form> 
  • Then, on dom ready: 然后,在dom准备好了:

      $(document).ready(function() { $('.val-req').rules('add', {required:true}); }); 
  • Validate method: 验证方法:

      function validate_form(form_id, callback) { var form = $('#'+form_id); $('.val-req').each(function() {$(this).rules('add', {required:true});}); $(form).validate({ errorElement: "span", errorClass: "val-error", validClass: "val-valid", errorPlacement: function(error, element) { $('#val-msg.'+$(element).attr('id')).innerHTML(error.html()); }, submitHandler: callback }); } 

As per my expectations, it should display error message in the place holder span in the form. 根据我的预期,它应该在表单中的占位符跨度中显示错误消息。

But, Problem 但是, 问题

Error on Chrome-Console : Uncaught TypeError: Cannot read property 'settings' of undefined Chrome-Console出错 :未捕获TypeError:无法读取未定义的属性“设置”

It is also giving error on other browsers. 它也在其他浏览器上出错。 Then, I tried to figure-out the problem and found: 然后,我试图弄清楚问题并发现:

 $('.val-req').rules('add', {required:true});   # This is causing the error

As, per my understanding and documentation -> This should be correct. 根据我的理解和文档 - >这应该是正确的。

Why would this cause the TypeError and what can I do to resolve it? 为什么会导致TypeError,我该怎么办才能解决它?

You have to add the rules after you call the validate plugin in the form element: 在表单元素中调用validate插件后,您必须添加规则:

$("form").validate()
$(yourElement).rules("add", {...})

I think your code is more complicated than it needs to be. 我认为你的代码比它需要的更复杂。 You should just have to call validate on document ready (assuming your form exists on document ready): 您应该只需要在文档就绪时调用validate (假设您的表单存在于文档就绪):

$(document).ready(function() {
    $(".val-req").addClass("required");
    $("#form_id").validate({
        errorElement: "span",
        errorClass: "val-error",
        validClass: "val-valid",
        errorPlacement: function(error, element) {
            $('#val-msg.' + $(element).attr('id')).html(error.html());
        },
        submitHandler: function () {
            this.submit();
        }
    });
});​

Example: http://jsfiddle.net/4vDGM/ 示例: http //jsfiddle.net/4vDGM/

You could also just add a class of required to required elements instead of adding them via JavaScript. 你也可以只添加一个类的required所需元素,而不是通过JavaScript添加。

Another thing you could do is add rules in the rules object of validate 's options: 您可以做的另一件事是在validate的选项的规则对象中添加规则:

$(document).ready(function() {
    $("#form_id").validate({
        rules: {
            myval: "required"
        },
        errorElement: "span",
        errorClass: "val-error",
        validClass: "val-valid",
        errorPlacement: function(error, element) {
            $('#val-msg.' + $(element).attr('id')).html(error.html());
        },
        submitHandler: function () {
            this.submit();
        }
    });
});​

Example: http://jsfiddle.net/GsXnJ/ 示例: http //jsfiddle.net/GsXnJ/

I was trying to modify the rules on a form that already had validation being set up, but i found my $(document).ready(...) code was executing before the main form validation was set up, so adding a short setTimeout cured this issue for me - eg 我试图在已经设置验证的表单上修改规则,但我发现我的$(document).ready(...)代码在主表单验证设置之前执行,所以添加一个简短的setTimeout为我解决了这个问题 - 例如

setTimeout(function() {
    $(yourElement).rules("add", {...})
}, 100);

The culprit is the method delegate(), which does not check whether a validator exists: 罪魁祸首是方法delegate(),它不检查验证器是否存在:

function delegate(event) {
  var validator = $.data(this[0].form, "validator"),
  eventType = "on" + event.type.replace(/^validate/, "");
  // this fixes handling the deleted validator:
  if (!validator) return;
  validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
}

I was searching for a solution and found it in a blog post. 我正在寻找解决方案并在博客文章中找到它。

Source: http://devio.wordpress.com/2012/07/18/fixing-jquery-validation-with-changing-validators/ 资料来源: http//devio.wordpress.com/2012/07/18/fixing-jquery-validation-with-changing-validators/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM