php - jQuery.validator.addMethod check username

1.6k views Asked by At

I am new to php and jQuery, I have googled a day but couldn't solve the problem. I want to check if the username is taken or not, but what I got is "Username is Already Taken" no matter what I enter. so here is my code:

$(document).ready(function(){
    $('#registration-form').validate({
    rules: {            
     username: {
            required: true,
            minlength: 3,
            maxlength: 25,
            letters: true,
            checkUsername: true,
        },        
      password: {
            required: true,
            minlength: 6,
            maxlength: 12
        },
    confirmpassword: {
            required: true,
            minlength: 6,
            maxlength: 12,
            equalTo: "#password"
        },        
      email: {
            required: true,
            email: true
        },  

     country:{
            required: true,
     }
            },

        highlight: function(element) {
            $(element).closest('.form-group').addClass('error');
            $(element).removeClass("valid");
        },
        success: function(element) {
            element
            .addClass('valid')
            .closest('.form-group').removeClass('error');
        }
  });

  $(".close, #close").click(function() {
        $("label.error").hide();
        $(".error").removeClass("error");
        $("input.valid").removeClass("valid");
    });

    $.validator.addMethod("letters", function(value, element) {
    return this.optional(element) || value == value.match(/^[a-zA-Z_]+$/);
    },"Letters and underscore only.");

    $.validator.addMethod("checkUsername", function(value, element){
        var response='';
        $.ajax({
            type: "POST",
            url: 'checkname.php',
            data:"username="+value,
            async:false,
            success:function(data){
            response = data;
            }
                });
            if(response == 0)
            {
                return true;
            }
            else
            {
            return false;
            }

    }, "Username is Already Taken");

}); 

Here is my checkname.php

<?php
include 'connect.php';

 if (isSet($_POST['username'])) {                                                               
  $username = mysql_real_escape_string($_POST['username']);                                  
  $check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'"); 
if (mysql_num_rows($check_for_username)>0) {
    echo "false";                                                                           
} else {
    echo "true";                                                                          
}
}


?>

Please help me, I am so frustrated .....

1

There are 1 answers

4
Sparky On BEST ANSWER

You should be using the remote method, which has already been tested and proven for this exact purpose. There is no reason to reinvent something that's already been done.

rules: {            
    username: {
        required: true,
        minlength: 3,
        maxlength: 25,
        letters: true,
        remote: {  // value of 'username' field is sent by default
            type: 'POST',
            url: 'checkname.php'
        }
    }
    ....

Your checkname.php

include 'connect.php';

if (isSet($_POST['username']))
{                                                               
    $username = mysql_real_escape_string($_POST['username']);

    $check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'"); 

    if (mysql_num_rows($check_for_username) > 0)
    {
        echo json_encode("Username is Already Taken");   
        // you could even try something like this:
        // echo json_encode($username . " is Already Taken");                                                                        
    } 
    else 
    {
        echo "true";                                                                          
    }
}

NOTE: mysql_ has been deprecated in PHP and should be replaced with mysqli or pdo_mysql. See: php.net/manual/en/function.mysql-query.php

Also see: jQuery Validate remote method usage to check if username already exists