如何强制 jQuery Validate 检查数据库中的重复用户名?

发布于 2024-11-09 09:30:09 字数 4424 浏览 0 评论 0原文

我即将进入这个项目的中期,因此由于代码草率,我不得不进行一些重写。我正在使用 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 的初学者,但我对这段代码感到非常不舒服。我是否走在正确的轨道上,还是应该在 rulesusername 下使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

仅此而已 2024-11-16 09:30:09

检查何时调用验证函数、username 的值是什么以及 output 的值是什么:是 true 还是 >“真”

我猜测后者:一个字符串,所以你可以这样做:

return output === "true" ? true : false; // I sincerely recommend using === here

因为如果你 return "false"; 将评估为 true 因为它是一个非空字符串 - 耶动态语言! :/

remote 示例:

$("#signup").validate( {
    rules: {
        username: {
            required: true,
            minlength: 5,
            remote: {
                url: "dbquery.php",
                type: "get",
                data: {
                    action: function () {
                        return "checkusername";
                    },
                    username: function() {
                        var username = $("#username").val();
                        return username;
                    }
                }
            }
        }
    },
    messages: {
        username: {
            required: "Enter a username"
        }
    },
    submitHandler: function(form) {
        form.submit();
    }
});

要设置自定义错误消息,您的 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 of output is: is it true or "true"?

I'm guessing latter: a string, so you could just do:

return output === "true" ? true : false; // I sincerely recommend using === here

Since if you return "false"; will evaluate to true because it's a non-empty string - yay dynamic langauges! :/

Example with remote:

$("#signup").validate( {
    rules: {
        username: {
            required: true,
            minlength: 5,
            remote: {
                url: "dbquery.php",
                type: "get",
                data: {
                    action: function () {
                        return "checkusername";
                    },
                    username: function() {
                        var username = $("#username").val();
                        return username;
                    }
                }
            }
        }
    },
    messages: {
        username: {
            required: "Enter a username"
        }
    },
    submitHandler: function(form) {
        form.submit();
    }
});

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.

野味少女 2024-11-16 09:30:09

当您添加addMethod时,您应该从服务器端返回truefalse

并且该值还必须从 addMethod 返回。

即像这样的东西

$.validator.addMethod("checkAvailability",function(value,element){
    var parameter="action=checkusername&username="+username;
    $.ajax({
          url: "dbquery.php",
          type: "POST",
          async: false,
          data: parameter
          success:function(output)
                 {
                    return output
                 }
     });
},"Sorry, this user name is not available");

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

$.validator.addMethod("checkAvailability",function(value,element){
    var parameter="action=checkusername&username="+username;
    $.ajax({
          url: "dbquery.php",
          type: "POST",
          async: false,
          data: parameter
          success:function(output)
                 {
                    return output
                 }
     });
},"Sorry, this user name is not available");
_蜘蛛 2024-11-16 09:30:09

我遇到了同样的问题,但我发现最简单的解决方案只是通过 php 编码为 json 后返回 true 或 false。

if ($users->username_exists())
{
    echo json_encode(FALSE);
}else{
    echo json_encode(TRUE);
}

I faced the same problem, But I find the easiest solution just return true or false after encoding into json through php.

if ($users->username_exists())
{
    echo json_encode(FALSE);
}else{
    echo json_encode(TRUE);
}
往日 2024-11-16 09:30:09

在服务器端脚本上,尝试返回 truefalse 而不是 availablenotavailable,因为这两个字符串相当于true

On your server side script, try returning true or false instead of available and notavailable, as both of those strings are equivalent to true.

十年九夏 2024-11-16 09:30:09

我的代码:

$( "#myform" ).validate({
  rules: {
    EMAIL: {
      remote: {
        type: "post",  
        url: "checkMail.php",           
        data:{checkUsername:function(){return $("#EMAIL").val()}            
        }
      }
    }
  },messages:{EMAIL:{remote: "Already taken!"}}
});

My code:

$( "#myform" ).validate({
  rules: {
    EMAIL: {
      remote: {
        type: "post",  
        url: "checkMail.php",           
        data:{checkUsername:function(){return $("#EMAIL").val()}            
        }
      }
    }
  },messages:{EMAIL:{remote: "Already taken!"}}
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文