简体   繁体   English

jQuery validate-添加规则会触发验证

[英]jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. 我有下面的代码,可以对表单中的字段执行一些条件验证。 The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required. 基本思想是,如果在一个字段中输入了某些内容,则应将此“组”中的所有字段都要求为必填项。

jQuery.validator.addMethod('readingRequired', function (val, el) {
    //Readings validation - if a reading or a date is entered, then they should all be ntered.
    var $module = $(el).closest('tr');
    return $module.find('.readingRequired:filled').length == 3;
});

//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
    'readingRequired': true
});

//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {

    var inputs = parent.find('input');    
    var required = false;

    if (parent.find('input:filled').length > 0) {
        required = true;
    }

    if (required) {
        inputs.addClass("readingRequired");
    }
    else {
        inputs.removeClass("readingRequired");
    }
}


//This is in the document.ready event:

$("input.reading").change(function () {
        SetReadingValidation($(this).closest("tr"));
    });

This works fine, and I've used pretty much the same code on other pages with success. 这很好用,我在其他页面上成功使用了几乎相同的代码。 The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. 这里的一个小问题是,当我在第一个文本框中输入一个值并从中跳出标签时,验证就会触发并显示错误消息。 This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. 在具有类似代码的其他页面上不会发生这种情况,而是要等到首次提交表单后进行验证。 Does anybody have any idea why this might be happening? 有人知道为什么会这样吗?

Hmm. You know how it goes, post a question and then find a solution yourself. 您知道进展如何,提出问题,然后自己找到解决方案。 Not sure why this works exactly, but changing my binding from: 不知道为什么这样可以正常工作,但是将我的绑定从:

$("input.reading").change(function () {
        SetReadingValidation($(this).closest("tr"));
    });

to

$("input.reading").blur(function () {
        SetReadingValidation($(this).closest("tr"));
    });

Seems to have solved this issue. 似乎已经解决了这个问题。 Would still appreciate being enlightened as to why that might be... 仍然很高兴能被启发了解为什么...

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

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