How can I force jQuery Validate to check for duplicate username in database?

前端 未结 5 1138
春和景丽
春和景丽 2021-01-03 11:52

I\'m coming into the middle of this project so I\'m having to do a bit of re-writing because of sloppy code. I am using jQuery 1.6.1 and Validate 1.8.1.

First, here\

5条回答
  •  不知归路
    2021-01-03 12:25

    Check when the validation function is getting called, what the value of username is and what the value of output is: is it true or "true"?

    I'm guessing latter: a string, so you could just do:

    return output === "true" ? true : false; // I sincerely recommend using === here
    

    Since if you return "false"; will evaluate to true because it's a non-empty string - yay dynamic langauges! :/

    Example with remote:

    $("#signup").validate( {
        rules: {
            username: {
                required: true,
                minlength: 5,
                remote: {
                    url: "dbquery.php",
                    type: "get",
                    data: {
                        action: function () {
                            return "checkusername";
                        },
                        username: function() {
                            var username = $("#username").val();
                            return username;
                        }
                    }
                }
            }
        },
        messages: {
            username: {
                required: "Enter a username"
            }
        },
        submitHandler: function(form) {
            form.submit();
        }
    });
    

    To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.

提交回复
热议问题