6

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...

Szymon Toda
  • 4,454
  • 11
  • 43
  • 62
Luis
  • 5,786
  • 8
  • 43
  • 62

5 Answers5

5

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.

DBD
  • 23,075
  • 12
  • 60
  • 84
Ian Stanway
  • 610
  • 8
  • 25
  • Hi, yes, but I wanna use a custom message error for each required field. If I change the jquery.validationEngine-en.js, I'm gonna change all the required error messages. I want something like "Email required", "Name required". – Luis Aug 12 '11 at 15:25
  • I'd found that site when i was looking for an answer, I thought it was going to work, but it seems that the code has some bugs, check the last line of the code: I also tried changing the line: newPrompt +=

    " + messages[j] + " "; To something like newPrompt += messages[j]; But its not working either... Thx for your help

    – Luis Aug 13 '11 at 14:02
  • The latest version of validationengine allows per-field error messages. I'd suggest using that now. – Ian Stanway Mar 14 '13 at 11:06
2
jQuery('#fieldId').validationEngine('showPrompt', 'This a custom msg', 'error', true)
  • error : the style of prompt , red

see the source code of this demo

khaled_webdev
  • 1,420
  • 15
  • 20
1

**Try this.. works for me :) Modified the promtText if the title is set using the following code in jquery.validationEngine.js

if (field.attr("title") != null) promptText = field.attr("title");

.**

        /**
     * Builds and shades a prompt for the given field.
     *
     * @param {jqObject} field
     * @param {String} promptText html text to display type
     * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
     * @param {boolean} ajaxed - use to mark fields than being validated with ajax
     * @param {Map} options user options
     */
     _buildPrompt: function (field, promptText, type, ajaxed, options) {

         // create the prompt
         var prompt = $('<div>');
         prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
         // add a class name to identify the parent form of the prompt
         if (field.is(":input"))
             prompt.addClass("parentForm" + methods._getClassName(field.parents('form').attr("id")));
         prompt.addClass("formError");

         switch (type) {
             case "pass":
                 prompt.addClass("greenPopup");
                 break;
             case "load":
                 prompt.addClass("blackPopup");
                 break;
             default:
                 /* it has error  */
                 //alert("unknown popup type:"+type);
         }
         if (ajaxed)
             prompt.addClass("ajaxed");

         // create the prompt content
         if (field.attr("title") != null)
            promptText = field.attr("title");
         var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);


         // create the css arrow pointing at the field
         // note that there is no triangle on max-checkbox and radio
         if (options.showArrow) {
             var arrow = $('<div>').addClass("formErrorArrow");

             //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
             var positionType = field.data("promptPosition") || options.promptPosition;
             if (typeof (positionType) == 'string') {
                 var pos = positionType.indexOf(":");
                 if (pos != -1)
                     positionType = positionType.substring(0, pos);
             }

             switch (positionType) {
                 case "bottomLeft":
                 case "bottomRight":
                     prompt.find(".formErrorContent").before(arrow);
                     arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
                     break;
                 case "topLeft":
                 case "topRight":
                     arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
                     prompt.append(arrow);
                     break;
             }
         }
         // Modify z-indexes  for jquery ui
         if (field.closest('.ui-dialog').length)
             prompt.addClass('formErrorInsideDialog');

         prompt.css({
             "opacity": 0,
             'position': 'absolute'
         });
         field.before(prompt);

         var pos = methods._calculatePosition(field, prompt, options);
         prompt.css({
             "top": pos.callerTopPosition,
             "left": pos.callerleftPosition,
             "marginTop": pos.marginTopSize,
             "opacity": 0
         }).data("callerField", field);

         if (options.autoHidePrompt) {
             setTimeout(function () {
                 prompt.animate({
                     "opacity": 0
                 }, function () {
                     prompt.closest('.formErrorOuter').remove();
                     prompt.remove();
                 });
             }, options.autoHideDelay);
         }
         return prompt.animate({
             "opacity": 0.87
         });
     },
     /**
     * Updates the prompt text field - the field for which the prompt
     * @param {jqObject} field
     * @param {String} promptText html text to display type
     * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
     * @param {boolean} ajaxed - use to mark fields than being validated with ajax
     * @param {Map} options user options
     */
     _updatePrompt: function (field, prompt, promptText, type, ajaxed, options, noAnimation) {

         if (prompt) {
             if (typeof type !== "undefined") {
                 if (type == "pass")
                     prompt.addClass("greenPopup");
                 else
                     prompt.removeClass("greenPopup");

                 if (type == "load")
                     prompt.addClass("blackPopup");
                 else
                     prompt.removeClass("blackPopup");
             }
             if (ajaxed)
                 prompt.addClass("ajaxed");
             else
                 prompt.removeClass("ajaxed");

             if (field.attr("title") != null)
                 promptText = field.attr("title");
             prompt.find(".formErrorContent").html(promptText);

             var pos = methods._calculatePosition(field, prompt, options);
             var css = { "top": pos.callerTopPosition,
                 "left": pos.callerleftPosition,
                 "marginTop": pos.marginTopSize
             };

             if (noAnimation)
                 prompt.css(css);
             else
                 prompt.animate(css);
         }
     },
1

This works <input type="text" value="" class="input full-width validate[required,custom[integer]" data-errormessage-custom-error="your message when wrong syntax" data-errormessage-value-missing="your meesage when field empty" /> For more details: Reference

siby
  • 23
  • 1
  • 7
1

You can set your own custom error message. In this script the "required" is already working now we are going to create a new rule "required_2". Step 1: Create a new case in jquery.validationEngine.js file Like

case "required_2":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;

Add add function for required_2

_required_2: function(field, rules, i, options) {
            switch (field.prop("type")) {
                case "text":
                case "password":
                case "textarea":
                case "file":
                default:
                    if (!($.trim(field.val())))
                        return options.allrules[rules[i]].alertText;
                    break;
                case "radio":
                case "checkbox":
                    var form = field.closest("form");
                    var name = field.attr("name");
                    if (form.find("input[name='" + name + "']:checked").size() == 0) {
                        if (form.find("input[name='" + name + "']").size() == 1)
                            return options.allrules[rules[i]].alertTextCheckboxe;
                        else
                            return options.allrules[rules[i]].alertTextCheckboxMultiple;
                    }
                    break;
                // required for <select>
                case "select-one":
                    // added by paul@kinetek.net for select boxes, Thank you
                    if (!field.val())
                        return options.allrules[rules[i]].alertText;
                    break;
                case "select-multiple":
                    // added by paul@kinetek.net for select boxes, Thank you
                    if (!field.find("option:selected").val())
                        return options.allrules[rules[i]].alertText;
            }
        }

Step:2 Now you can change in your language file "jquery.validationEngine-en.js" for english

"required_2": { // Add your regex rules here, you can take telephone as an example
                    "regex": "none",
                    "alertText": "* This field is required by mohan",
                    "alertTextCheckboxMultiple": "* Please select an option",
                    "alertTextCheckboxe": "* This checkbox is required",
                    "alertTextDateRange": "* Both date range fields are required"
                },

Step:3 Now almost is done and you can use this in your html fields for example

<input value="" class="validate[required_2] text-input" type="text" name="req1" id="req1" data-prompt-position="topRight:-70" />