如何强制 jQuery Validate 检查数据库中的重复用户名?
我即将进入这个项目的中期,因此由于代码草率,我不得不进行一些重写。我正在使用 jQuery 1.6.1 和 Validate 1.8.1。
首先,这是运行后端的 PHP (dbquery.php):
include("../includes/dbconnection.php");
session_start();
$location='';
$action='';
if($_GET['action']=='')
$action=$_POST['action'];
else
$action=$_GET['action'];
if($action=='checkusername'){
$error='';
$username=$_GET['username'];
// exclude denied account
$checkuserquery=mysql_query("Select * from database_users as user LEFT OUTER JOIN database_approval as approval on user.user_id=approval.approval_user_id where (approval.approval_status IS NULL or approval.approval_status <> 4) and user_username='".$username."'");
$checkuserresult=mysql_numrows($checkuserquery);
if($checkuserresult>0) {
$error = 'false';
} else {
$error = 'true';
}
echo $error;
}
我正在尝试使用 jQuery Validate 脚本动态查询数据库中的现有用户名。我要么遇到两个极端:它永远不起作用,要么它总是返回给定的用户名。
我相信问题是我无法获取用户名变量的输入值。当我在函数(输出)
中创建警报(用户名)
时,它什么也不返回。我的假设是 .val()
仅在页面加载时才起作用,因此我在输入中输入的任何内容由于某种原因都不起作用。
这是我重新编写并从在线源复制的 jQuery:
$(document).ready(function(){
$.validator.addMethod("checkAvailability",function(value,element){
var username = $("#username").val();
$.ajax({
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function(output) {
return output;
}
});
},"Sorry, this user name is not available");
// jQuery Validation script
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
checkAvailability: true // remote check for duplicate username
},
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
我只是 jQuery 的初学者,但我对这段代码感到非常不舒服。我是否走在正确的轨道上,还是应该在 rules
和 username
下使用 remote:
?有人告诉我,由于我尝试验证的输入值的动态性质,remote
方法将不起作用。
我遇到的另一个主要问题是仅当数据库中已存在用户名时才显示远程错误消息。不幸的是,它显示 dbquery.php 返回的是 true
还是 false
。如果我尝试使用现有的用户名,它会返回 false
,然后我重写一个返回 true
的新用户名,该消息不会消失。同样,当我写入用户名并返回 true
时,我仍然收到远程错误消息。
原始编码器引用 getXMLHTTP
并使用 ActiveXObject
。他编写的方法似乎有点过时,所以我试图使代码更现代一些并清理它。
5/25 - 我正在编辑此内容以包含旧的原始 JavaScript 代码,该代码可以工作,但使用的是我想摆脱的过时方法(我已经删除了以下代码并替换为 jQuery上面):
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
//validate username
function validateUsername(username){
var strURL="dbquery.php?action=checkusername&username="+username;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
if(req.responseText=='notavailable'){
document.getElementById("errorusername").style.display="block";
document.getElementById("errorusername").innerHTML="<div id=\"errors\"><strong>"+username+"</strong> is already taken by another user.</div>";
error = true;
}
else{
error = false;
document.getElementById("errorusername").style.display="none";
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
I'm coming into the middle of this project so I'm having to do a bit of re-writing because of sloppy code. I am using jQuery 1.6.1 and Validate 1.8.1.
First, here's the PHP which runs the back-end (dbquery.php):
include("../includes/dbconnection.php");
session_start();
$location='';
$action='';
if($_GET['action']=='')
$action=$_POST['action'];
else
$action=$_GET['action'];
if($action=='checkusername'){
$error='';
$username=$_GET['username'];
// exclude denied account
$checkuserquery=mysql_query("Select * from database_users as user LEFT OUTER JOIN database_approval as approval on user.user_id=approval.approval_user_id where (approval.approval_status IS NULL or approval.approval_status <> 4) and user_username='".$username."'");
$checkuserresult=mysql_numrows($checkuserquery);
if($checkuserresult>0) {
$error = 'false';
} else {
$error = 'true';
}
echo $error;
}
I'm trying to use jQuery Validate script to query the database for existing usernames on the fly. I either get two extremes: it never works or it always spits back given username as taken.
I believe the problem is that I cannot grab the input value of the username variable. When I create alert (username)
within function (output)
, it returns nothing. My assumption is that .val()
is only working when the page loads thus anything I'm typing into the input isn't working for some reason.
Here's the jQuery I've re-written and copied from sources online:
$(document).ready(function(){
$.validator.addMethod("checkAvailability",function(value,element){
var username = $("#username").val();
$.ajax({
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function(output) {
return output;
}
});
},"Sorry, this user name is not available");
// jQuery Validation script
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
checkAvailability: true // remote check for duplicate username
},
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
I am only a beginner with jQuery but am getting my hands pretty dirty with this code. Am I on the right track or should I use remote:
under rules
and username
? I've been told that the remote
method won't work because of the dynamnic nature of the input value I'm trying to validate.
The other major problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true
or false
. If I try an existing username, it returns false
, then I rewrite a new username that returns true
, the message doesn't go away. Similarly, when I write a username and it returns true
, I still get the remote error message.
The original coder was referencing getXMLHTTP
and using ActiveXObject
. The method he programmed seemed a little outdated so I'm trying to make the code a little more contemporary and clean it up.
5/25 - I am editing this to include the OLD original JavaScript code which works but is using the outdated method which I'd like to get away from (I have since removed the following code and replaced with jQuery above):
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
//validate username
function validateUsername(username){
var strURL="dbquery.php?action=checkusername&username="+username;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
if(req.responseText=='notavailable'){
document.getElementById("errorusername").style.display="block";
document.getElementById("errorusername").innerHTML="<div id=\"errors\"><strong>"+username+"</strong> is already taken by another user.</div>";
error = true;
}
else{
error = false;
document.getElementById("errorusername").style.display="none";
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
检查何时调用验证函数、
username
的值是什么以及output
的值是什么:是true
还是>“真”
?我猜测后者:一个字符串,所以你可以这样做:
因为如果你
return "false";
将评估为true
因为它是一个非空字符串 - 耶动态语言! :/remote
示例:要设置自定义错误消息,您的 PHP 文件必须返回该消息而不是 false,因此 echo
"Sorry, this user name is not available"
in你的 PHP 文件。Check when the validation function is getting called, what the value of
username
is and what the value ofoutput
is: is ittrue
or"true"
?I'm guessing latter: a string, so you could just do:
Since if you
return "false";
will evaluate totrue
because it's a non-empty string - yay dynamic langauges! :/Example with
remote
:To set a custom error message your PHP file must return the message instead of false, so echo
"Sorry, this user name is not available"
in your PHP file.当您添加addMethod时,您应该从服务器端返回true或false。
并且该值还必须从 addMethod 返回。
即像这样的东西
While you adding addMethod you should return true or false from server side.
and also that value have to be returned from addMethod.
ie something like this
我遇到了同样的问题,但我发现最简单的解决方案只是通过 php 编码为 json 后返回 true 或 false。
I faced the same problem, But I find the easiest solution just return true or false after encoding into json through php.
在服务器端脚本上,尝试返回
true
或false
而不是available
和notavailable
,因为这两个字符串相当于true
。On your server side script, try returning
true
orfalse
instead ofavailable
andnotavailable
, as both of those strings are equivalent totrue
.我的代码:
My code: