如何强制jQuery Validate检查数据库中的重复用户名? [英] How can I force jQuery Validate to check for duplicate username in database?

查看:67
本文介绍了如何强制jQuery Validate检查数据库中的重复用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进入这个项目的中间,所以我不得不做一些重写,因为代码很粗糙。我正在使用jQuery 1.6.1和Validate 1.8.1。

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.

首先,这是运行后端的PHP( dbquery.php ):

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;
} 

我正在尝试使用jQuery Validate脚本在数据库中查询现有用户名在飞行中。我要么得到两个极端:它永远不会工作,或者总是吐出给定的用户名。

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.

我认为问题是我无法获取用户名变量的输入值。当我在函数(输出)中创建 alert(用户名)时,它什么都不返回。我的假设是 .val()仅在页面加载时起作用,因此我输入的任何内容都因某些原因而无效。

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.

这是我在网上重新编写和复制的jQuery:

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();
        }
    });

});

我只是jQuery的初学者,但是这个代码让我的手很脏。我是在正确的轨道上还是应该在规则用户名下使用 remote: code>?我被告知远程方法不起作用,因为我正在尝试验证输入值的动态特性。

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.

我遇到的另一个主要问题是当数据库中已存在用户名时,只显示远程错误消息。不幸的是,它显示dbquery.php是否以 true false 的形式返回。如果我尝试使用现有用户名,它会返回 false ,然后我重写一个返回 true 的新用户名,消息不会不要走开同样,当我写一个用户名并返回 true 时,我仍然收到远程错误信息。

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.

原文编码器引用 getXMLHTTP 并使用 ActiveXObject 。他编程的方法似乎有点过时,所以我试图使代码更现代化并清理它。

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 - 我是编辑它以包含OLD原始JavaScript代码,但它正在使用我想要离开的过时方法(我已经删除了以下代码并替换为上面的jQuery

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);
    }     
}


推荐答案

检查当调用验证函数时,用户名的值是什么, output 的值是:是吗 true true

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

因为如果你返回 false; 将评估为 true ,因为它是一个非空字符串 - yay动态langauges! :/

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

远程示例:

$("#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 对不起,这个用户名不可用在你的PHP文件中。

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.

这篇关于如何强制jQuery Validate检查数据库中的重复用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆