如何自定义jquery验证引擎消息错误

时间:2011-08-08 20:41:29

标签: jquery html jquery-validation-engine

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

Link of the plugin

默认使用以下内容时:

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

你没有在里面输入任何东西,你会收到消息:“*字段必需”,这很好,但我想要一些类似:“*名称要求”......

我的.js文件只有这个:

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

任何帮助将不胜感激,我已经有几天试图完成这个......

5 个答案:

答案 0 :(得分:5)

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

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

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

它们覆盖了来自validationengine的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">

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

答案 1 :(得分:2)

jQuery('#fieldId').validationEngine('showPrompt', 'This a custom msg', 'error', true)
  
      
  • 错误:提示样式,红色
  •   

查看此demo

的源代码

答案 2 :(得分:1)

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

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

答案 3 :(得分: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);
         }
     },

答案 4 :(得分: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" /> 有关详细信息:Reference