Jörn Zaefferer has created a nice jQuery plugin for validating forms. Along with the standard required and formatting validation, it also allows validation using remote calls. Unfortunately for us .Net users, the plugin was not written to interface with ASP.Net webservices. Below is an example how the plugin can be modified to retrieve results from an ASP.Net webservice.
Searching through the plugin source (example), you will find the below section of code that makes the remote call. The validation extends the standard $.ajax call and checks whether the response is true or false.
// http://docs.jquery.com/Plugins/Validation/Methods/remote
remote: function(value, element, param)
{
...
$.ajax($.extend(true,
{
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
success: function(response)
{
if ( response )
{
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
} else
{
var errors = {};
errors[element.name] = response || validator.defaultMessage( element, "remote" );
validator.showErrors(errors);
}
...
While this is valid for most languages, with ASP.Net 3.5 Microsoft modified the JSON response of webservices. Webservices accessed under .Net 3.5 will have the JSON response within a .d attribute. Because of this, any remote validation request against these types of webservices will generate a null exception. To handle this new change, we need to extract the true JSON response from the response. Adding the following line to the $.ajax success function will now get the true response.
// http://docs.jquery.com/Plugins/Validation/Methods/remote
remote:
function(value, element, param)
{
...
$.ajax($.extend(
true,
{
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
success:
function(response)
{
response = response.d
if ( response )
{
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
}
else
{
var errors = {};
errors[element.name] = response || validator.defaultMessage( element, "remote" );
validator.showErrors(errors);
}
...