JQuery用户名验证

时间:2011-04-20 14:52:11

标签: php jquery validation username

我是JQuery的新手,并尝试编写一个脚本来检查用户名的可用性。我的问题是,无论我输入什么内容,我总会回复“此用户名已被使用。”

JQuery来源:

$(document).ready(function() {

jQuery.validator.addMethod("usernameCheck", function(username) {
   var isSuccess = false;
   $.ajax({ url: "username_availability.php",
            data: "username=" + username,
            async: false,
            success:
                function(msg) { isSuccess = msg === "TRUE" ? true : false }
          });
    return isSuccess;
},"");

$("#register_form").validate({
    onkeyup:false,
    rules: {
        username: {
            required: true,
            minlength: 3,
            usernameCheck: true    // remote check for duplicate username
        }
    },
    messages: {
        username: {
            required: "username is required.",
            minlength: jQuery.format("username must be at least {0} characters in length."),
            usernameCheck: "This username is already in use."
        }
    }
});

PHP来源:

include('database_connection.php');                                  
if (isset($_POST['username'])) {                                                               
    $username = mysql_real_escape_string($_POST['username']);                                  
    $check_for_username = mysql_query("SELECT user_id FROM users WHERE username='$username'"); 
    if (mysql_num_rows($check_for_username)) {
        echo "TRUE";                                                                           
    } else {
        echo "FALSE";                                                                           //No Record Found - Username is available
    }
}
?>

HTML来源:

<input class="username" id="username" type="text" name="username" value="" maxlength="20" />&nbsp;

非常感谢

5 个答案:

答案 0 :(得分:1)

将ajax调用选项type设置为'POST'。此外,AJAX不会阻止return isSuccess

您可以查看jQuery Validate提供的远程验证。

http://docs.jquery.com/Plugins/Validation/Methods/remote#options

更改规则。

rules: {
        username: {
            required: true,
            minlength: 3,
            remote: 'username_availability.php' // remote check for duplicate username
        }
    },

看看这些例子。

答案 1 :(得分:0)

我想知道这条线是不是问题:

data: "username=" + username,

尝试将其更改为正确的数组,因为我不相信jQuery会自动解析这种格式,尤其是对于POST数据。另外,在$ .ajax调用中设置类型:'post'的选项,因为jQuery会自动将$ .ajax请求解析为GET,并且您在PHP脚本中使用POST。

答案 2 :(得分:0)

尝试更改PHP源以返回“1”或“0”:

include('database_connection.php');                                  
if (isset($_POST['username'])) {                                                               
    $username = mysql_real_escape_string($_POST['username']);                                  
    $check_for_username = mysql_query("SELECT user_id FROM users WHERE username='$username'"); 
    if (mysql_num_rows($check_for_username)) {
        echo "TRUE";                                                                           
    } else {
        echo "FALSE";                                                                           //No Record Found - Username is available
    }
}
?>

然后更改您的JS以将其解析为整数:

success:
 function(msg) { 
   isSuccess = parseInt(msg);
 }

答案 3 :(得分:0)

您可以使用以下内容,只需将其更改为您的用户名(我使用电子邮件地址作为用户名。我使用空表格单元格id =“emailError”来保留邮件。

jQuery:

    $('#email').keyup(function(){
      $.ajax({
        type: 'POST',
        url: 'ajax.checkEmail.php',
        data: {e:$('#email').val()},
        success: function(data){
          if(data == 'true'){
            $('#emailError').html('This email is already used');
          }else{
            $('#emailError').html('');
          }
        }
      })
    });

PHP(ajax.checkEmail.php):


  include('inc.php');

  $query  = 'SELECT COUNT(*) FROM tblcustomers WHERE email = "'.$_POST['e'].'"';
  $result = $dbO->getSingleResult($query);

  if($result > 0)
    print 'true';
  else
    print 'false';

答案 4 :(得分:0)

这只是检查了相同的代码

      jQuery.validator.addMethod("usernameCheck", function(username) {
      var isSuccess = false;
      $.ajax({ url: "checkusr.php",
      data: "username=" + username,
      async: false,
      success:
      function(msg) { 

      if(msg ==0)
      {
  isSuccess=false;
      }
      else 
      {

       isSuccess=true;
      }
        }


       });

        return isSuccess;
         },"Username not available");

PHP SIDE CODE

           if ($obj->checkUsername($_GET['username'],"artist")> 0 )
       {
       echo 0;
        }
    else 
    {
  echo 1;
 }

  }