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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6117901/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:33:11  来源:igfitidea点击:

How can I force jQuery Validate to check for duplicate username in database?

javascriptjqueryvalidationjquery-validate

提问by micah

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.

我正在进入这个项目的中间,所以由于草率的代码,我不得不重新编写一些代码。我正在使用 jQuery 1.6.1 和验证 1.8.1。

First, here's the PHP which runs the back-end (dbquery.php):

首先,这是运行后端的 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;
} 

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.

我正在尝试使用 jQuery Validate 脚本动态查询数据库中的现有用户名。我要么得到两个极端:它从不工作,要么总是在给定用户名时回吐。

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.

我相信问题是我无法获取用户名变量的输入值。当我alert (username)在 内创建时function (output),它不返回任何内容。我的假设是.val()只有在页面加载时才有效,因此我在输入中输入的任何内容由于某种原因都不起作用。

Here's the jQuery I've re-written and copied from sources online:

这是我重新编写并从在线资源中复制的 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();
        }
    });

});

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 rulesand username? I've been told that the remotemethod won't work because of the dynamnic nature of the input value I'm trying to validate.

我只是 jQuery 的初学者,但我的手很脏,这段代码。我是在正确的轨道上还是应该使用remote:under rulesand username?有人告诉我,remote由于我试图验证的输入值的动态特性,该方法将不起作用。

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 trueor 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.

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

The original coder was referencing getXMLHTTPand 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.

原始编码器正在引用getXMLHTTP和使用ActiveXObject. 他编写的方法似乎有点过时,所以我试图使代码更具现代感并进行清理。

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):

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

回答by Halcyon

Check when the validation function is getting called, what the value of usernameis and what the value of outputis: is it trueor "true"?

检查何时调用验证函数,值username是什么以及值output是什么:是true还是"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 truebecause it's a non-empty string - yay dynamic langauges! :/

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

Example with remote:

示例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.

要设置自定义错误消息,您的 PHP 文件必须返回消息而不是 false,因此请"Sorry, this user name is not available"在您的 PHP 文件中回显。

回答by Mahesh KP

While you adding addMethodyou should return trueor falsefrom server side.

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

and also that value have to be returned from addMethod.

并且该值必须从 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");

回答by Sharp Coders

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

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

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

回答by minboost

On your server side script, try returning trueor falseinstead of availableand notavailable, as both of those strings are equivalent to true.

在您的服务器端脚本中,尝试返回trueorfalse代替availableand notavailable,因为这两个字符串都等价于true

回答by gokhan

My code:

我的代码:

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