jQuery validator and a custom rule that uses AJAX
For anyone else who stumbles upon this, validate supports 'remote' method, which may not have existed in 2010:
https://jqueryvalidation.org/remote-method/
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
}
});
It took me forever to figure out how to get a jsonified string containing the value of an element in the page into the remote request- this is the result of a combination of many hours and trying many search results.
Key points:
async:false
has been deprecated,the function call right after
remote:
is the key for creating the data string with the element's value. Trying to access a current value from the form afterdata:
was returning a blank value for the field withdataType
set as json.$("#EmailAddress").rules("add", { required: true, remote: function () { // the function allows the creation of the data string // outside of the remote call itself, which would not // return a current value from the form. var emailData = "{'address':'" + $('#SignupForm :input[id$="EmailAddress"]').val() + "'}"; var r = { url: "foobar.aspx/IsEmailAvailable", type: "post", dataType: "json", contentType: "application/json; charset=utf-8", cache: false, data: emailData, dataFilter: function(response) { this.email_run = true; //fix for race condition with next button return isAvailable(data); //return true or false } }; return r; }, messages: { remote: "* Email in use" } });
.ASPX page:
<input id="EmailAddress" required name="Email" type="email" placeholder="Email Address*" runat="server"/>
C# Code Behind:
[WebMethod]
public static object IsEmailAvailable(string address){...}
Formatting the response object:
function isAvailable(data) {
var response = JSON.parse(getJsonObject(data));
return (response.isAvailable === "True") ? true : false;
};
//transform response string to a JavaScript Object()
//http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/
function getJsonObject(data) {
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
};
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async
. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Something like:
function myValidator() {
var isSuccess = false;
$.ajax({ url: "",
data: {},
async: false,
success:
function(msg) { isSuccess = msg === "true" ? true : false }
});
return isSuccess;
}
Warning:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().