问题
Does anyone have a working example of a username checker using jquery validation and jquery addmethod?
Something like this:
$("#register_form").validate({
onkeyup:false,
rules: {
username: {
required: true,
minlength: 3,
usernameCheck: true // remote check for duplicate username
},
});
jQuery.validator.addMethod("usernameCheck", function(username) {
var isSuccess = false;
$.ajax({
url: "username_availability.php",
data: "username=" + username,
async: false,
type: "POST",
success:
function(msg) {
isSuccess = parseInt(msg);
}
});
return isSuccess;
},"");
I've been looking all over Google for days, and I've noticed a number of threads like this that go unanswered or unsolved with a high view count. So if someone could provide a link or a solution, I'm sure a lot of JQuery noobs would benefit and be glad. :)
Hey guys, thanks a lot for all your help. I managed to find what I was looking for though.
The "milk example"? Really? It exists?
--Yes my son, it exists and it's awesome: http://jquery.bassistance.de/validate/demo/milk/
回答1:
I think your problem is that the the success method isn't being called by the time you return. You can change your code to be:
jQuery.validator.addMethod("usernameCheck", function(username) {
var result = $.ajax({
url: "username_availability.php",
data: {username: username},
async: false,
type: "POST"
}).responseText;
return result === '1';
},"");
回答2:
Use the remote
type instead of making up your own.
$("#register_form").validate({
onkeyup:false,
rules: {
username: {
required: true,
minlength: 3,
remote:'username_availability.php'
},
});
It will pass a parameter of username=foo
to your username_availability.php
page. Return true or false from that page.
来源:https://stackoverflow.com/questions/5733253/jquery-username-validation