how to customize jquery validation engine message error

Luis picture Luis · Aug 8, 2011 · Viewed 23.2k times · Source

I'm trying to make a customized error message with the validationEngine plugin

Link of the plugin

By default when you use something like:

<input value="" class="validate[required]" type="text" name="name" id="name"/>

And you don't type a thing in it, you'll get the message: "* Field required", which is nice, but I want something like: "* Name required"...

I only have this on my .js file:

$("#Form_Name").validationEngine();

Any help will be appreciated, I already have a few days trying to accomplish this...

Answer

Ian Stanway picture Ian Stanway · Aug 12, 2011

All you need to do is amend the messages in the jquery.validationEngine-en.js (or whatever language it is you want if not English). Bear in mind that all fields of the validation type you change will display the same message.

This is also the place you can add your own custom validation and messages.

\Edit - Ahh I see what you mean. Well, I can't take any credit for this, but a company called iPragmaTech came up with a solution for the same problem using the title attribute of the field.

They override buildprompt function from the validationengine and added functionality to pick the customized error message.

Here is their code below:

var buildPrompt = $.validationEngine.buildPrompt;
$.validationEngine.buildPrompt = function(caller, promptText, type, ajaxed) {
  // Get the rules to map the message for a method
  var rulesRegExp = /\[(.*)\]/;
  var getRules = rulesRegExp.exec($(caller).attr('class'));
  var str = getRules[1];
  var pattern = /\[|,|\]/;
  var rules = str.split(pattern);
  //Check if title attribute present in the element
  //otherwise we shall use default error message
  if ($(caller).attr('title')) {
    var getMessages = rulesRegExp.exec($(caller).attr('title'));
    var str = getMessages[1];
    var pattern = /\[|,|\]/;
    var messages = str.split(pattern);

    var j = 0;
    newPrompt = "";
    for ( var i = 0; i < rules.length; i++) {
     rules = $.validationEngine.settings.allrules[rules[i]]
      if (rules) {
        if (promptText.indexOf(rules.alertText) != -1) {

          newPrompt += "
<p class="errorMsg">" + messages[j] + "

";

        }
        j++;
      }
    }
    promptText = newPrompt;
  }

  buildPrompt(caller, promptText, type, ajaxed);
}
</p>

They added error messages in the ‘title’ attribute and this gives the flexibility to customize the error message for different field. So here is the example where custom error message can be added:

<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20]]" name="user" id="user" title="[* Desired username is required,* No special caracters allowed for  Desired username,* Desired username should have characters between 0 and 20]" type="text">

I hope this solves your problem.