简体   繁体   中英

Django. Using Jquery Validate and ajax to make sure username is unique

I want to use jquery validate() to make sure that there aren't users with equal nickname (or username, in my model it is called nickname, but it is the same).

the model field looks like this:

    nickname = models.CharField(max_length=75, unique=True, null=True)

I want to use ajax, this is the 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: {
        ...
});

and in 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'))

This doesn't work, it behaves as if the username field contains an error and displays the error message all the time.

Simply use the remote method included in the plugin.

  • The URL of your server-side function is the parameter
  • You do not need to specify data because the field's data is sent by default.
  • You do not need to specify GET because it's the default method.


$('#form_user').validate({
    rules: {
        nickname: {
            required: true,
            maxlength: 75,
            remote: "/profiles/check_nickname/"
        }
    },
    ....
});

Your server-side function at /profiles/check_nickname/ must echo or return true when you want validation to pass. It must echo or return false or a JSON string when you want validation to fail. The JSON string will become the error message if you use it, otherwise, the default error message will be shown.

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.


SIDE-NOTE to answer why your custom solution is broken:

Quote OP:

"This doesn't work, it behaves as if the username field contains an error and displays the error message all the time."

That's because you're not using the addMethod() method properly. By inserting your message text into an element, you're manually bypassing how the plugin automatically creates and displays error messages.

The custom error message is supposed to be the third parameter, after the entire function...

$.validator.addMethod("checkNickname", function(){ // 1st, NAME for method
    // your validation function here               // 2nd, LOGIC for method
}, "Nickname already exists");                     // 3rd, ERROR MESSAGE for method

Then the plugin will know how & when to automatically toggle the message. If the message is in the wrong place, use standard .validate() options such as errorPlacement , errorElement , etc. to customize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM