gpt4 book ai didi

jquery - 如何让 JQuery 验证在空输入上调用远程规则

转载 作者:行者123 更新时间:2023-12-01 01:33:12 24 4
gpt4 key购买 nike

如何让 JQuery 验证在空字段上触发远程规则?服务器决定该字段是否为必填字段,因此即使字段为空,我也需要在调用 valid 时触发远程规则 - 目前,如果字段为空,则不会调用该规则.

最佳答案

创建了一个新的验证器方法,该方法不调用可选函数,并设置为同步处理 ajax 调用。

$.validator.addMethod("synchronousRemote", function (value, element, param) {

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) {
return previous.valid;
}

previous.old = value;
var validator = this;
this.startRequest(element);
var data = {};
data[element.name] = value;
var valid = "pending";
$.ajax($.extend(true, {
url: param,
async: false,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
success: function (response) {
validator.settings.messages[element.name].remote = previous.originalMessage;
valid = response === true || response === "true";
if (valid) {
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
var errors = {};
var message = response || validator.defaultMessage(element, "remote");
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = valid;
validator.stopRequest(element, valid);
}
}, param));
return valid;
}, "Please fix this field.");

关于jquery - 如何让 JQuery 验证在空输入上调用远程规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com