php jQuery Validator Plugin - 检查 mysql 数据库中现有的用户名/电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19539115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validator Plugin - check for existing Username/Email in mysql database
提问by user2910809
I've successfully created a form that submits and adds users to a mysql database, and form validation with 'jQuery Validator' pluginworks great for everything except checking to see if the username already exists in the database...
我已经成功创建了一个提交用户并将用户添加到 mysql 数据库的表单,并且使用“jQuery Validator”插件的表单验证适用于所有事情,除了检查用户名是否已存在于数据库中...
I've just spent about 8 hours reading and trying to figure out a way to define a new method with the 'jQuery Validator' plugin. I just can't seem to understand how I would go about checking the database for the entered username or email and return whether it already exists or not using jQuery.
我刚刚花了大约 8 个小时阅读并试图找出一种使用“jQuery Validator”插件定义新方法的方法。我似乎无法理解我将如何检查数据库中输入的用户名或电子邮件,并使用 jQuery 返回它是否已经存在。
My code:
我的代码:
<script src="../assets/js/main.js"></script>
<script src="../assets/js/ajax.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<!-- FORM VALIDATION -->
<script type="text/javascript">
jQuery.validator.addMethod("checkExists",
function(value, element) {
//No idea what to call here
},
"Username already exists."
);
//<![CDATA[
$(window).load(function(){
$("form").validate({
rules: {
username: {minlength: 3, required: true, checkExists: true},
email: {email: true, required: true},
pass1: {minlength: 3, required: true},
pass2: {minlength: 3, required: true, equalTo: "#pass1"},
country: {required: true},
tandc: {required: true},
},
messages: {
username: {required: "You need to enter a Username."},
email: {required: "You need to enter an Email Address."},
pass1: {required: "You need to enter a Password."},
pass2: {required: "You need to enter your password again.", equalTo: "Your passwords don't match."},
country: {required: "You need to tell us where you live."},
tandc: {required: "You need to read and agree to the Terms and Conditions to use CGE."}
},
showErrors: function(errorMap, errorList) {
$.each(this.successList, function(index, value) {
return $(value).popover("hide");
});
return $.each(errorList, function(index, value) {
var _popover;
console.log(value.message);
_popover = $(value.element).popover({
trigger: "manual",
placement: "right",
content: value.message,
template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>"
});
_popover.data("popover").options.content = value.message;
return $(value.element).popover("show");
});
}
});
});//]]>
</script>
If anyone clever could please amend my code to show me how I should have done it, it would be a great help - I feel like I'm about to go crazy!
如果任何聪明的人都可以修改我的代码以向我展示我应该如何完成它,那将是一个很大的帮助 - 我觉得我快要疯了!
Thanks in advance, can't wait to see the solution :-)
提前致谢,迫不及待想看到解决方案:-)
EDIT - This is my current code
编辑 - 这是我当前的代码
Nothing seems to happen at all, I feel like I'm closer though:
似乎什么也没发生,但我觉得我更接近了:
CURRENT CODE:
当前代码:
signup.php
注册.php
$(window).load(function(){
$("form").validate({
rules: {
username: {minlength: 3, required: true},
email: {email: true, required: true, remote: {url: "./validation/checkUnameEmail.php", type : "post"}},
pass1: {minlength: 3, required: true},
pass2: {minlength: 3, required: true, equalTo: "#pass1"},
country: {required: true},
tandc: {required: true}
},
checkUnameEmail.php
checkUnameEmail.php
<?php
include_once(".../php_includes/db_conx.php");
$email = urldecode($_POST['email']);
$result = mysqli_query($db_conx, "SELECT * FROM users WHERE email = '$email' LIMIT 1;");
$num = mysqli_num_rows($result);
if($num == 0){
echo "true";
} else {
echo "E-Mail-Adresse schon registriert.";
}
mysqli_close($db_conx);
?>
*db_conx.php*
*db_conx.php*
<?php
$db_conx = mysqli_connect("localhost", "root", "root", "membership");
//Evlauate the connection
if (mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}
?>
回答by Jenson M John
$.validator.addMethod("checkExists", function(value, element)
{
var inputElem = $('#register-form :input[name="email"]'),
data = { "emails" : inputElem.val() },
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: validateEmail.php,
dataType: "json",
data: data,
success: function(returnData)
{
if (returnData!== 'true')
{
return '<p>This email address is already registered.</p>';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
OR
或者
You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote
您可以改用远程方法,它允许您进行远程检查: http://docs.jquery.com/Plugins/Validation/Methods/remote
Eg.
例如。
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkUnameEmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkUnameEmail.php //Eg.
checkUnameEmail.php //例如。
<?php
$registeredEmail = array('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]');
$requestedEmail = $_REQUEST['email'];
if( in_array($requestedEmail, $registeredEmail) ){
echo 'false';
}
else{
echo 'true';
}
?>
回答by Canaan Etai
js code
js代码
username: {
required: true,
minlength: 5,
remote: '/userExists'
},
Php code to check if exist and return messages
检查是否存在并返回消息的 PHP 代码
public function userExists()
{
$user = User::all()->lists('username');
if (in_array(Input::get('username'), $user)) {
return Response::json(Input::get('username').' is already taken');
} else {
return Response::json(Input::get('username').' Username is available');
}
}
回答by Mayank Dudakiya
For WordPress & PHP
对于 WordPress 和 PHP
Most important thing is instead or return true or false, need to echo 'true' or 'false'
最重要的是,或者返回 true 或 false,需要 echo 'true' 或 'false'
jQuery or JS
jQuery 或 JS
email: {
required: true,
minlength: 6,
email: true,
remote:{
url : 'your ajax url',
data: {
'action': 'is_user_exist',
},
},
},
WordPress or PHP Backend Code
WordPress 或 PHP 后端代码
In backend you will automatically get the value of field via GET method.
在后端,您将通过 GET 方法自动获取字段的值。
/*
*@ Check user exists or not
*/
if( !function_exists('is_user_exists_ajax_function') ):
function is_user_exists_ajax_function() {
$email = $_GET['email'];
if( empty($email) && is_email($email) ):
wp_send_json_error( new \WP_Error( 'Bad Request' ) );
endif;
$is_email = email_exists( $email );
if($is_email):
echo 'false';
else:
echo 'true';
endif;
wp_die();
}
add_action( 'wp_ajax_is_user_exist', 'is_user_exists_ajax_function' );
add_action( 'wp_ajax_nopriv_is_user_exist', 'is_user_exists_ajax_function' );
endif;