虽然我认为不是为此进行不显眼的验证(目的是验证每次按键时的输入 - 它对用户友好),但这种方法有一个解决方法:
您可以将这些非常少的行(标记为//this is my code
)添加到您的jquery.validate.js
并缩小它,或者您可以创建一个新.js
文件并添加休闲代码。
请注意,如果您想摆脱onkeyup
某些特定的input
(而不是某些特定的规则,即远程),有一种特定且简单的方法可以做到这一点,您可以在 jquery 站点中找到它。
此代码将仅忽略事件remote
规则keyup
并正常验证其他事件(即required
)keyup
和focuseout
事件。
(function ($) {
jQuery.validator.setDefaults({
onkeyup: function (element) {
$(element).data('firedON', 'keyup') //this is my code
if (element.name in this.submitted || element == this.lastElement) {
this.element(element);
}
}
});
$.validator.methods.remote = function (value, element, param) {
if ($(element).data('firedON') == 'keyup') {
$(element).data('firedON') = '';
return "dependency-mismatch"; //this 'if' is my code(thats it)
}
if (this.optional(element))
return "dependency-mismatch";
var previous = this.previousValue(element);
if (!this.settings.messages[element.name])
this.settings.messages[element.name] = {};
previous.originalMessage = this.settings.messages[element.name].remote;
this.settings.messages[element.name].remote = previous.message;
param = typeof param == "string" && { url: param} || param;
if (previous.old !== value) {
previous.old = value;
var validator = this;
this.startRequest(element);
var data = {};
data[element.name] = value;
$.ajax($.extend(true, {
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
success: function (response) {
validator.settings.messages[element.name].remote = previous.originalMessage;
var valid = response === true;
if (valid) {
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
} else {
var errors = {};
var message = (previous.message = response || validator.defaultMessage(element, "remote"));
errors[element.name] = $.isFunction(message) ? message(value) : message;
validator.showErrors(errors);
}
previous.valid = valid;
validator.stopRequest(element, valid);
}
}, param));
return "pending";
} else if (this.pending[element.name]) {
return "pending";
}
return previous.valid;
}
} (jQuery));
更新
上面的代码肯定可以工作,但我想注意到我试图通过不带整个函数来使代码更整洁,即:
var remote = $.validator.methods.remote;
$.validator.methods.remote = function(a,b,c){
if ($(element).data('firedON') == 'keyup') return "dependency-mismatch";
return remote(a,b,c);
}
但它失败了,因为在将旧函数存储在局部remote
变量中后,' this
'将引用其他地方,我无法修复this
此代码,所以我带来了上面的代码。