基本上,我需要测试子域是否存在,所以我在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!
即使它不存在!对此有任何帮助,谢谢!
答案 0 :(得分:1)
您正在使用AJAX请求来检索验证结果,但是:当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
选项已弃用,您可以通过执行remote validation来解决此问题:
$( "#form" ).validate({
rules: {
subdomain: {
required: true,
uniqueSubdomain: true,
remote: {
url: "ajax.php",
type: "post",
data: 'subdomain='+ value
}
}
}
});
答案 1 :(得分:1)
在虚假案例中添加以下行
$("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" });
答案 2 :(得分:1)
另一个完美的解决方案是,我们需要返回验证方法的标志。
$.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!");
答案 3 :(得分:1)
您的验证和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!");