2010-08-26 131 views
2

我真的試圖避免問這個問題。我在這個插件上看到了很多關於SO的文章,但他們仍然不太明白。現在我有一個新的帳戶註冊表單,我正在嘗試編寫一個用於驗證唯一用戶名的自定義方法。我想認爲下列代碼應該起作用:jQuery驗證插件

$.validator.addMethod(
     "uniqueUsername", 
     function(value, element) { 
      $.post(
       "http://" + location.host + "/scripts/ajax/check_username.php", 
       { 
        username: value 
       }, 
       function(response) { 
        if(response == 'true') { 
         return true; 
        } else { 
         return false; 
        } 
       } 
      ); 
     }, 
     "This username is already taken." 
    ); 

不幸的是它似乎像插件就不管回調函數的移動。我發現有人建議做類似如下:

var result = false; 
    $.validator.addMethod(
     "uniqueUsername", 
     function(value, element) { 
      $.post(
       "http://" + location.host + "/scripts/ajax/check_username.php", 
       { 
        username: value 
       }, 
       function(response) { 
        if(response == 'true') { 
         result = true; 
        } else { 
         result = false; 
        } 
       } 
      ); 
      return result; 
     }, 
     "This username is already taken." 
    ); 

但似乎是因爲它存儲的值,然後在接下來的事件將設置任何的價值是有一個延遲。你們推薦什麼?

回答

2

由於這是一個異步檢查,因此需要更多的檢查(不能從這樣的函數返回值,在您的情況下它將始終爲false)。內置的方法是remote,像這樣使用:

$("form").validate({ 
    rules: { 
    username: { 
     remote: { 
     url: "http://" + location.host + "/scripts/ajax/check_username.php", 
     type: "post" 
     } 
    } 
    } 
}); 

這將發佈一個username: valueofElement,因爲規則是名爲username的元素。如果驗證通過,您的服務器端腳本應返回true,否則返回false ...如果用戶名已被佔用,則返回false

You can read more about the remote option here,包括如果需要傳遞額外的數據參數。

+0

活泉活泉,你是男人:d – 2010-08-26 17:34:43

-1

js代碼

username: { 
     required: true, 
     minlength: 5, 
     remote: '/userExists' 
     }, 

PHP代碼,以檢查是否存在,並返回消息

public function userExists() 
{ 
    $user = User::all()->lists('username'); 
    if (in_array(Input::get('username'), $user)) { 
     return Response::json(Input::get('username').' is already taken'); 
    } else { 
     return Response::json(Input::get('username').' Username is available'); 
    } 
} 
+0

沒有好。當你想要驗證通過時,PHP **必須**'echo true'。任何其他響應(例如JSON字符串)都表示_failed_驗證。由於驗證失敗,表單無法提交。此外,不知道爲什麼你回答了一個已經有了可接受的答案的四歲的問題。 – Sparky 2014-08-20 05:38:13