我正在尝试使用下面的代码向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;
?>
最佳答案
在这里,你不能用一个定制的方法来完成这项工作,因为你需要验证插件来知道这是一个远程(或者更重要的是,异步)请求。
幸运的是,它有内置的功能来提供帮助。您可以在这里使用remote
而不是自定义方法,因此请完全放弃自定义方法并更改如下:
uniqueEmail: true
为此:
remote: { url: "availability.php", type: "post" }
然后将错误消息添加到
messages
中,如下所示:email: { remote: "Email is already taken" }
还可以将PHP端更改为match,返回
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
}
?>