6

我正在尝试使用 validationEngine 插件制作自定义错误消息

插件链接

默认情况下,当您使用以下内容时:

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

而且您无需在其中输入任何内容,您将收到消息:“* 必填字段”,这很好,但我想要类似:“* 必填字段”...

我的 .js 文件中只有这个:

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

任何帮助将不胜感激,我已经有几天的时间来尝试完成这个......

4

5 回答 5

5

您需要做的就是修改 jquery.validationEngine-en.js 中的消息(或者任何您想要的语言,如果不是英语的话)。请记住,您更改的验证类型的所有字段都将显示相同的消息。

这也是您可以添加自己的自定义验证和消息的地方。

\编辑 - 啊,我明白你的意思了。好吧,我对此不以为然,但是一家名为iPragmaTech的公司使用该字段的标题属性为同一问题提出了解决方案。

它们覆盖来自验证引擎的 buildprompt 函数,并添加了选择自定义错误消息的功能。

下面是他们的代码:

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>

他们在 'title' 属性中添加了错误消息,这为自定义不同字段的错误消息提供了灵活性。因此,这是可以添加自定义错误消息的示例:

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

我希望这能解决你的问题。

于 2011-08-12T14:54:06.063 回答
2
jQuery('#fieldId').validationEngine('showPrompt', 'This a custom msg', 'error', true)
  • 错误:提示的样式,红色

查看此演示的源代码

于 2013-04-11T08:42:59.647 回答
1

这有效 <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" /> 有关更多详细信息:参考

于 2013-09-11T05:17:25.170 回答
1

**试试这个..对我有用:) 如果使用 jquery.validationEngine.js 中的以下代码设置标题,则修改 promtText

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);
         }
     },
于 2012-04-26T05:14:27.033 回答
1

您可以设置自己的自定义错误消息。在这个脚本中,“required”已经在工作了,现在我们将创建一个新规则“re​​quired_2”。第 1 步:在 jquery.validationEngine.js 文件中创建一个新案例 Like

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

为 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;
            }
        }

步骤:2 现在您可以将语言文件“jquery.validationEngine-en.js”更改为英文

"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"
                },

步骤:3 现在几乎完成了,例如,您可以在 html 字段中使用它

<input value="" class="validate[required_2] text-input" type="text" name="req1" id="req1" data-prompt-position="topRight:-70" />
于 2012-03-28T12:33:29.550 回答