基本上,我需要测试子域是否存在,所以我在我的jQuery验证规则中添加了一个方法jQuery:
$.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!,即使它不存在!有什么可以帮忙的,谢谢!
发布于 2014-04-09 11:01:24
您正在使用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选项,所以可以通过执行远程验证来解决这个问题。
$( "#form" ).validate({
rules: {
subdomain: {
required: true,
uniqueSubdomain: true,
remote: {
url: "ajax.php",
type: "post",
data: 'subdomain='+ value
}
}
}
});发布于 2014-04-09 11:13:13
在false情况下添加以下行
$("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!");FYI:我相信您的错误容器是"div",如果没有,请将下面的行更改为
$("errorContainer.error").css({ display: "none" });发布于 2014-04-09 11:19:17
另一个完美的解决方案是,我们需要返回验证方法的标志。
$.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!");https://stackoverflow.com/questions/22960279
复制相似问题