[英]AJAX Jquery Validation not working while submitting the form
基本上,我需要测试子域是否存在,因此我向jQuery Validate规则添加了方法uniqueSubdomain
:
$.validator.addMethod("uniqueSubdomain", function(value, element) {
$.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain='+ value,
cache: false,
success: function(msg)
{
alert(msg);
// if the subdomain exists, it returns a string "true"
if(msg == "true"){
return false; // already exists
}else{
return true; // subdomain is free to use
}
}
})}, "sub-domain already exists!");
并在规则中:
subdomain: {
required: true,
uniqueSubdomain: true
},
但是似乎只显示sub-domain already exists!
即使它不存在! 任何帮助,谢谢!
您正在使用AJAX请求来检索验证结果, 但BUT :当ajax返回结果时验证可能已经完成,因为您正在处理异步调用。
您需要使ajax请求同步,以便验证不会处理,结果将返回async: false
。
就像是:
$.validator.addMethod("uniqueSubdomain", function(value, element) {
$.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain='+ value,
async: false,
cache: false,
success: function(msg)
{
alert(msg);
// if the subdomain exists, it returns a string "true"
if(msg == "true"){
return false; // already exists
}else{
return true; // subdomain is free to use
}
}
})}, "sub-domain already exists!");
由于不赞成使用async
选项,因此您可以通过执行远程验证来解决它:
$( "#form" ).validate({
rules: {
subdomain: {
required: true,
uniqueSubdomain: true,
remote: {
url: "ajax.php",
type: "post",
data: 'subdomain='+ value
}
}
}
});
在错误的情况下添加以下行
$("div.error").css({ display: "none" });
举个例子
$.validator.addMethod("uniqueSubdomain", function(value, element) {
$.ajax({
type: "POST",
url: "ajax.php",
async: false,
data: 'subdomain='+ value,
cache: false,
success: function(msg)
{
//alert(msg);
// if the subdomain exists, it returns a string "true"
if(msg == "true"){
return false; // already exists
}else{
$("div.error").css({ display: "none" });
return true; // subdomain is free to use
}
}
});
}, "sub-domain already exists!");
仅供参考:我相信您的错误容器是“ div”,如果不是,请将以下行更改为
$("errorContainer.error").css({ display: "none" });
另一个完美的解决方案是,我们需要返回用于验证方法的标志。
$.validator.addMethod("uniqueSubdomain", function(value, element) {
var isFlag;
$.ajax({
type: "POST",
url: "ajax.php",
async: false,
data: 'subdomain='+ value,
cache: false,
success: function(msg)
{
//alert(msg);
// if the subdomain exists, it returns a string "true"
if(msg == "true"){
isFlag = false; // already exists
}else{
//$("div.error").css({ display: "none" });
isFlag = true; // subdomain is free to use
}
}
});
return isFlag;
}, "sub-domain already exists!");
您的验证和ajax并行运行。 完成验证后,ajax可能无法完成。 为此,您需要使用async:false
。 并且可以使用以下(已测试);
$.validator.addMethod("uniqueSubdomain", function(value, element) {
var domainOk = false
$.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain='+ value,
cache: false,
success: function(msg) {
// if the subdomain exists, it returns a string "true"
if(msg == "true"){
domainOk = false
}else{
domainOk = true;
}
}
});
return domainOk;
}, "sub-domain already exists!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.