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

12,477

Solution 1

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.

Solution 2

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

Solution 3

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);
}
Share:
12,477
micah
Author by

micah

I specialize in responsive, inclusive user interfaces using semantic HTML, modern CSS and component-based Javascript. I develop professional apps and websites, incorporating thoughtful user experience with the following principles: accessibility, progressive enhancement, SEO and fast performance. I also work with designers to create style guides and design patterns. Cross-platform and cross-browser testing is a must. I am regularly working to improve my experience, whether on the full-stack of technology or the front-end.

Updated on June 05, 2022

Comments

  • micah
    micah almost 2 years

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