jQuery验证 - 添加规则会导致验证失败

时间:2011-03-14 11:51:20

标签: 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 = $(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"));
    });

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

1 个答案:

答案 0 :(得分:0)

嗯。你知道它是怎么回事,发一个问题,然后自己找一个解决方案。不确定为什么这可以正常工作,但改变我的绑定:

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

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

似乎已经解决了这个问题。仍然希望能够了解为什么会这样......

相关问题