我想在用戶註冊帳戶時在用戶名字段上進行客戶端驗證。此驗證應檢查在用戶提交表單之前是否已獲取用戶名。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>
而且,這裏是做驗證的部分觀點:
視圖,您需要與當前選擇的用戶名一個AJAX調用服務器並返回一個true或如果假用戶名已經在數據庫中。 – Gocht