我想做一个客户端验证的用户名字段时,用户正在注册一个帐户。此验证应检查在用户提交表单之前是否已使用用户名。在
我目前已经使用jqueryvalidate实现了基本的客户端验证:http://jqueryvalidation.org/
在Django实现这一点的推荐方法是什么?是否可以将此解决方案与jQuery validate集成?在
更新以下是我的js和html代码:
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();
}
}
}
}
}
});
});
HTML格式:
^{pr2}$
另外,下面是执行部分验证的视图:def check_username(request):
username = request.POST.get('username', False)
if not username:
return HttpResponseBadRequest("Invalid username")
return HttpResponse(User.objects.filter(username=username).exists())