Ajax Validation Using jquery?
I using jquery validation plugin.
In my form i need to check whether the nick name is already in use or not.
For that they are providing remote
key to make ajax call. For me the ajax call is working
correctly and returning true or false. But its allowing even if the returned value is false,
which should not happen.
My validation code looks like,
$(function() {
$("#myform").validate({
rules: {
fullName: {
required: true,
minlength: 5
},
nickName: {
required: true,
minlength: 4,
alphaNumeric: true,
remote: {
url: "NickNameChecker",
type: "post",
data: {
nickName: function() {
return $("#nickName").val();
}},
success: function(data) {
return data;
}
}
}
},
messages: {
fullName: {
required: "Please Enter Your Full Name.",
minlength: "Full Name should have minimum 5 letters."
},
nickName: {
required: true,
minlength: "Nick Name should contain minim开发者_如何学编程um 4 letters.",
remote: "This nickname is already in use."
}
}
});
});
Any suggestions would be appreciative!!!
Thanks!
Solution:
The solution is in my code only.
I just removed the success part and tried. Its working great!
(Expanded explanation from comment above):
The success
option is not valid for jQuery validate's remote validation. You should be able to just specify a URL to access for validation that returns true or a falsy value/error message:
The serverside resource is called via $.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
See the documentation for remote for more information on how to use the option. Your code would probably look something like this:
$(function() {
$("#myform").validate({
rules: {
fullName: {
required: true,
minlength: 5
},
nickName: {
required: true,
minlength: 4,
alphaNumeric: true,
remote: {
url: "NickNameChecker",
type: "post",
data: {
nickName: function() {
return $("#nickName").val();
}
}
}
},
messages: {
fullName: {
required: "Please Enter Your Full Name.",
minlength: "Full Name should have minimum 5 letters."
},
nickName: {
required: true,
minlength: "Nick Name should contain minimum 4 letters.",
remote: "This nickname is already in use."
}
}
});
});
The jQuery Validation team advised another way to handle non-boolean APIs in this GitHub issue.
The proposed method takes advantage of jQuery.ajax()'s dataFilter property.
form.validate({
rules: {
username: {
required: true,
remote: {
url: "users2.json.php",
dataFilter: function(data) {
var json = JSON.parse(data);
if(json.status === "success") {
return '"true"';
}
return "\"" + json.error + "\"";
}
}
}
}
});
精彩评论