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

Javascript jQuery验证-添加规则会触发验证,javascript,jquery,jquery-validate,Javascript,Jquery,Jquery Validate,我有下面这样的代码来对表单中的字段执行一些条件验证。其基本思想是,如果在一个字段中输入了某些内容,则该“组”中的所有字段都应为必填字段 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 = $(

我有下面这样的代码来对表单中的字段执行一些条件验证。其基本思想是,如果在一个字段中输入了某些内容,则该“组”中的所有字段都应为必填字段

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"));
    });

这很好,我在其他页面上使用了几乎相同的代码,并取得了成功。这里的一个小问题是,当我在第一个文本框中输入一个值并从中取出一个选项卡时,将触发验证并显示一条错误消息。这不会发生在具有类似代码的其他页面上,而是验证会等待表单首次提交。有人知道为什么会发生这种情况吗?

嗯。你知道怎么回事,发一个问题,然后自己找到解决办法。不确定这到底是为什么,但将我的绑定更改为:

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

似乎已经解决了这个问题。我仍然希望你能明白为什么

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