Using the remote function of jquery validation

后端 未结 8 674
逝去的感伤
逝去的感伤 2020-12-16 03:12

I\'m trying to figure out how I can turn this:

$(\'#username\').blur(function(){
    $.post(\'register/isUsernameAvailable\', 
           {\"username\":$(\'#         


        
相关标签:
8条回答
  • 2020-12-16 03:50

    The easiest way to accomplish this is to simply return true, an error message as a string, or false from your server-side resource. According to the jQuery validate documentation for remote:

    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.

    This means if you can change your server-side code to return true in the event of successful validation or an error message ("username already in use") in the event of unsuccessful validation, you could just write the following remote rule:

    remote: {
        type: 'post',
        url: 'register/isUsernameAvailable',
        data: {
            'username': function () { return $('#username').val(); }
        },
        dataType: 'json'
    }
    

    You could also simply return true or false from your server-side resource and define the error message on the client. In that case you would have the above rule and then a property in the messages object:

    messages: {
        username: {
            remote: "username already in use"
        }
    }
    
    0 讨论(0)
  • 2020-12-16 03:57
    rules: {
            username: {
                minlength: 6,
                maxlength: 12,
                remote: 'register/isUsernameAvailable',
             }
            }
    

    You need to pass username

    0 讨论(0)
提交回复
热议问题