2015-09-28 30 views
0

我想在用戶註冊帳戶時在用戶名字段上進行客戶端驗證。此驗證應檢查在用戶提交表單之前是否已獲取用戶名。Django中重複的用戶名客戶端驗證

使用jQuery驗證我目前已經實現基本的客戶端驗證:http://jqueryvalidation.org/

什麼是推薦的方法在Django做到這一點?是否有可能將這個解決方案與jQuery驗證?

更新下面是我的JS和HTML代碼:

<script> 
    function getCookie(name) { 
     var cookieValue = null; 
     if (document.cookie && document.cookie != '') { 
      var cookies = document.cookie.split(';'); 
      for (var i = 0; i < cookies.length; i++) { 
       var cookie = jQuery.trim(cookies[i]); 
       // Does this cookie string begin with the name we want? 
       if (cookie.substring(0, name.length + 1) == (name + '=')) { 
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
        break; 
       } 
      } 
     } 
     return cookieValue; 
    } 

    var csrftoken = getCookie('csrftoken'); 


    function csrfSafeMethod(method) { 
     // these HTTP methods do not require CSRF protection 
     return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
    } 
    $.ajaxSetup({ 
     beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && !this.crossDomain) { 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
     } 
    }); 


    $(document).ready(function() { 
     $('#register-form').validate({ // initialize the plugin 
     rules: { 
      username: { 
      required: true, 
      remote: { 
       url: "/check-username", 
       type: "post", 
       data: { 
       username: function() { 
        return $("#id_username").val(); 
       } 
       } 
      } 
      } 
     } 
     }); 
    }); 
    </script> 

HTML:

<form action="/accounts/register/" id="register-form" method="post">{% csrf_token %} 
    {{form.username}} 
    ... 
</form> 

而且,這裏是做驗證的部分觀點:

​​
+0

視圖,您需要與當前選擇的用戶名一個AJAX調用服務器並返回一個true或如果假用戶名已經在數據庫中。 – Gocht

回答

0

以下是文檔中遠程驗證的一個修改示例:

http://jqueryvalidation.org/remote-method/

$("#myform").validate({ 
    rules: { 
    username: { 
     required: true, 
     email: true, 
     remote: { 
     url: "/check-username", 
     type: "post", 
     data: { 
      username: function() { 
      return $("#username").val(); 
      } 
     } 
     } 
    } 
    } 
}); 

然後,所有你需要的是確實

username = request.POST.get('username', None) 
# probably you want to add a regex check if the username value is valid here 
if not username: 
    return HttpResponseBadRequest("Invalid username") 
return HttpResponse(User.objects.filter(username=username).exists()) 
+0

好的,謝謝你。但是,似乎您必須提交表單才能進行驗證? –

+0

不,它會發送第一個ajax請求,詢問服務器用戶名是否有效。只有當服務器返回true並且所有其他字段的驗證也爲真時,用戶表單纔會(允許)提交。 –

+0

好吧,明白了。我只是試圖實現這一點,但似乎阿賈克斯沒有通過。實際上,現在,當字段出現錯誤時,錯誤消息會一直存在,並且在成功輸入時不會被刪除。 –