views:

2728

answers:

2

I've created a method for jquery's validator plugin, that works like the remote rule. The difference is that I'd like to display a dynamic error message (based on the ajax response).

jQuery.validator.addMethod("duplicate", function(value, element, params) { 
    var object_settings = this.settings;
    params.data[$(element).attr("name")] = value;
    $.post(params.url, params.data, function(response) {
     if (response == 'true'){ return true; }
     else {
      object_settings.messages[element.name] = response;
      return false;
     }
    }, 'text');
}, '');

It works...sort of....it sets the message, but doesn't display it initially (if you validate the field a second time, the message is displayed).

Any suggestions?

(maybe the remote rule offers this functionality...I couldn't find anything in the documentation)

+2  A: 

Here's the solution....needed to call the showErrors function of the object:

jQuery.validator.addMethod("duplicate", function(value, element, params) { 
    var validator = this;
    params.data[element.name] = value;
    $.post(params.url, params.data, function(response) {
     if (response == 'true'){ return true; }
     else {
      var errors = {};
      errors[element.name] =  response;
      validator.showErrors(errors);
      return false;
     }
    }, 'text');
}, '');

Taken from "remote" in jquery.validate.js (lines 917 - 919)

timborden
A: 

Where do I set the params to the function?

PPardo
In the validate call:$("form").validate({ rules: { name: {required: true,duplicate: {url: "file",data: { var1: "var1",var2: "var2",var3: "var3"}}}}
timborden