我正在尝试使用下面的代码为jQuery验证插件添加一个新方法。我的目标是检查电子邮件地址是否已存在于数据库(MySQL)中。如果是,它将通知用户注册另一个电子邮件地址。不知何故,总是返回的结果是“已经收到电子邮件”。
这些是validate.js中的代码:
$(document).ready(function(){
$.validator.addMethod("uniqueEmail", function(value, element) {
$.ajax({
type: "POST",
url: "availability.php",
data: value,
success: function(exist)
{
if(exist>0) {
return true;
} return false;
}
});
} ,"Email is already taken");
$('#signup form').validate({
rules: {
firstname: {
required: true,
minlength:3
},
lastname: {
required: true,
minlength: 3
},
affiliation: {
required: true,
},
occupation: {
required: true,
},
email: {
required: true,
email: true,
uniqueEmail: true
},
password: {
minlength: 6,
required: true
},
repassword: {
equalTo: "#password"
}
},
messages: {
firstname: {
minlength: "Your first name should be more than 3 characters"
},
lastname: {
minlength: "Your last name should be more than 3 characters"
},
},
success: function(label) {
label.text('OK!').addClass('valid');
}
});
});
这些是我的php文件中的代码:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/db.inc.php';
$email = strtolower($_POST['email']);
$email = mysqli_real_escape_string($link, $email);
$sql = "SELECT * FROM bradduser WHERE email='$email'";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
echo $num;
?>
答案 0 :(得分:3)
您无法使用自定义方法完成此操作,因为您需要验证插件才能知道这是远程(或更重要的是,异步)请求。
幸运的是,它具有内置功能,可以提供帮助。您可以在此处使用remote
代替自定义方法,因此请完全保留自定义方法并更改此内容:
uniqueEmail: true
为此:
remote: { url: "availability.php", type: "post" }
然后将错误消息添加到messages
,如下所示:
email: { remote: "Email is already taken" }
同时更改您的PHP端以匹配,返回true
或false
,如下所示:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/db.inc.php';
$email = strtolower($_POST['email']);
$email = mysqli_real_escape_string($link, $email);
$sql = "SELECT * FROM bradduser WHERE email='$email'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0) {
echo "false"; //validation fails, email in use
} else {
echo "true"; //validation passes
}
?>