In the jQuery Validate docs it shows an example of using a remote validation call to pass additional values to server side validation script/resource:
http://docs.jquery.com/Plugins/Validation/Methods/remote#code
Here’s the sample code:
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
}
});
Why do I need to use a function to set the username data parameter?:
username: function() {
return $("#username").val();
}
rather than just:
username: $("#username").val()
I’ve tried both methods and sure enough the second method doesn’t assign username: a value.
I did set a breakpoint in the jQuery Validate code in the remote method function:
remote: function(value, element, param) {
...
}
to try and understand what is happening here, but I am really none-the-wiser.
jQuery.fn.validate(config)is used to set up the validation rules, not actually perform validation. The entire{rules: /* */ }object is evaluated exactly when that happens.If you include
in the rules object, that expression will be evaluated immediately and the element’s value at that moment will be saved.
If you instead pass
as the value, this function will be evaluated when the
remotevalidator is invoked and the AJAX call is made, whenjQuery.paramflattens thedataproperty into a string.Note that this validator merges its entire config object into every AJAX call it makes, so all other options acceptable in the normal ajax settings object can be set this way, not just
data.