这让我疯了。通过使用addMethod规则中的ajax到我的验证器,通过php检查我的数据库中是否存在电子邮件地址。我已经确认php文件正在输出" true"或"假"在找到电子邮件时是否正确,但即使响应正确且值为false,规则也始终返回true。
这是规则:
$.validator.addMethod("isExisting", function() {
var checkemail=$("#email").val();
console.log('Email: '+checkemail); // shows email populated correctly
if(checkemail){
$.ajax({
type: 'post',
url: 'checkemail.php',
data: {email:checkemail,},
success: function(response){
console.log(response); // properly returns text "false" when email not found
var exists = (response=="false") ? false : true;
console.log('exists = '+exists); // is properly false
return exists; // returns false
}
});
}
});
在验证器中 - (" isExisting"错误消息始终弹出,无论电子邮件是否真的存在):
$("#signupform").validate({
errorLabelContainer: "#errors",
errorPlacement: function (error, element) {
error.insertAfter(element);
$(element).addClass(errorClass).removeClass(validClass);
},
rules: {
fullname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true,
isExisting: true
},
areacode: {
required: true,
digits: true,
minlength: 3
},
prefix: {
required: true,
digits: true,
minlength: 3
},
num: {
required: true,
digits: true,
minlength: 4
},
address: {
required: true,
},
city: {
required: true,
},
noRobot: {
isCaptcha: true,
}
},
messages: {
fullname: {
required: "Please enter your full name.<br />",
minlength: "Please enter your First and Last name.<br />"
},
email: {
required: "Please enter your email address.<br />",
email: "Please enter a valid email address.<br />",
isExisting: "There is already an account with that email address.<br />"
},
areacode: {
required: "Please enter your areacode.<br />",
minlength: "Your areacode should be 3 digits. »XXX« XXX-XXXX<br />"
},
prefix: {
required: "Please enter your phone number prefix.<br />",
minlength: "Your phone number Prefix should be 3 digits. XXX »XXX«-XXXX<br />"
},
num: {
required: "Please enter your phone number suffix.<br />",
minlength: "Your phone number Suffix should be 4 digits. XXX XXX-»XXXX«<br />"
},
address: {
required: "Please enter your Street Address for pick-up service.<br />"
},
city: {
required: "Please enter your town or city.<br />"
},
noRobot: {
isCaptcha: "Please verify that your are not a spam Robot.<br />"
}
}
});
我认为&#34; isExisting:true&#34;只有在从响应返回真值时才会验证为true。 (沮丧地抓着头......)
checkemail.php:
else{
$result = mysqli_query($connect, "SELECT * FROM `customer_info` WHERE `email`='$email' LIMIT 1");
$num = mysqli_num_rows($result);
if($num > 0){
echo "true";
}
else {
echo "false";
}
}
mysqli_close($connect);
答案 0 :(得分:0)
我的理解是,当响应有效时,验证器方法应该返回true。在您的情况下,有效的响应是没有匹配的电子邮件,因此如果AJAX调用返回false,您希望返回true。
使这个方法 isUnused 而不是 isExisting 以避免布尔混淆可能不那么令人困惑,但你也需要更改checkemail.php。 / p>
编辑:忽略上面的答案,我明显误解了这个问题。
我认为真正的问题是异步调用。尝试在ajax调用中设置 async:false 。