我想使用jquery validate()来确保不存在具有相同昵称(或用户名,在我的模型中称为昵称,但它是相同的)的用户。
模型字段如下所示:
nickname = models.CharField(max_length=75, unique=True, null=True)
我想使用ajax,这是javascript:
$.validator.addMethod("checkNickname", function(){
var nickname = $("#nickname").val();
if (nickname == ''){
return false
};
$.ajax({
type: "GET",
url: "/profiles/check_nickname/",
data: {'nickname':nickname},
success: function(response){
if (response == "True"){
return true
}
else {
$("#help_nickname").text("Nickname already exists")
return false
}
}
})
});
$('#form_user').validate({
rules: {
nickname: {
required: true,
maxlength: 75,
checkNickname: true,
}
},
errorElement: "span",
messages: {
...
});
在views.py中:
def check_nickname(request):
if request.is_ajax():
nickname_new = request.GET.get('nickname', '')
if Profiles.objects.exclude(user=request.user).filter(nickname=nickname_new).exists():
return HttpResponse(False)
else:
return HttpResponse(True)
else:
return HttpResponseRedirect(reverse('profiles:login'))
这不起作用,它的行为就像用户名字段包含错误并始终显示错误消息。
最佳答案
只需使用 the remote
method包含在插件中。
- 服务器端函数的 URL 是参数
- 您无需指定
data
,因为默认情况下会发送该字段的数据。 - 您无需指定
GET
,因为它是默认方法。
$('#form_user').validate({
rules: {
nickname: {
required: true,
maxlength: 75,
remote: "/profiles/check_nickname/"
}
},
....
});
您位于 /profiles/check_nickname/
的服务器端函数必须在需要时 echo
或 return
true
验证通过。当您希望验证失败时,它必须 echo
或 return
false
或 JSON 字符串。如果您使用JSON字符串,则该字符串将成为错误消息,否则将显示默认错误消息。
<小时/>The serverside resource is called via
jQuery.ajax
(XMLHttpRequest) and gets a key/value pair corresponding to the name of the validated element and its value as aGET
parameter. The response is evaluated asJSON
and must betrue
for valid elements, and can be anyfalse
,undefined
ornull
for invalid elements, using the default message; or a string, eg."That name is already taken, try peter123 instead"
to display as the error message.
附注回答您的自定义解决方案为何失效:
引用OP:
"This doesn't work, it behaves as if the username field contains an error and displays the error message all the time."
那是因为您没有使用 the addMethod()
method适本地。通过将消息文本插入到元素中,您可以手动绕过插件自动创建和显示错误消息的方式。
自定义错误消息应该是第三个参数,在整个函数之后...
$.validator.addMethod("checkNickname", function(){ // 1st, NAME for method
// your validation function here // 2nd, LOGIC for method
}, "Nickname already exists"); // 3rd, ERROR MESSAGE for method
然后插件将知道如何以及何时自动切换消息。如果消息位置错误,请使用 standard .validate()
options如errorPlacement
、errorElement
等来自定义。
关于javascript - Django 。使用 Jquery Validate 和 ajax 确保用户名是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273159/