[英]jQuery validate - adding a rule causes validation to fire
我有下面的代碼,可以對表單中的字段執行一些條件驗證。 基本思想是,如果在一個字段中輸入了某些內容,則應將此“組”中的所有字段都要求為必填項。
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"));
});
似乎已經解決了這個問題。 仍然很高興能被啟發了解為什么...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.