javascript - Django 。使用 Jquery Validate 和 ajax 确保用户名是唯一的

标签 javascript jquery ajax django jquery-validate

我想使用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/ 的服务器端函数必须在需要时 echoreturn true验证通过。当您希望验证失败时,它必须 echoreturn 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 a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null 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() optionserrorPlacementerrorElement等来自定义。

关于javascript - Django 。使用 Jquery Validate 和 ajax 确保用户名是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273159/

相关文章:

javascript - 如何使百分比符号小于数字?

javascript - 如何在 Android Webview 中加载网页之前注入(inject) javascript?

jquery - 使用 jQuery 在页面上切换 DIV

javascript - 三个文本输入到一个 POST 名称

php - 我在将文件移动到我想要的文件夹时遇到问题

javascript - 使用映射遍历对象数组。 javascript 中的过滤器、归约器或 Object.keys()

javascript - 如何淡入标题中的所有元素?

javascript - 如何在单击按钮时同时运行表单操作和单击事件

javascript - 为什么innerHTML 调用不起作用?

javascript - JQuery ajax 在开关切换时执行多次