jQuery 如何自定义jquery验证引擎消息错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6988275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to customize jquery validation engine message error
提问by Luis
I'm trying to make a customized error message with the validationEngine plugin
我正在尝试使用validationEngine插件制作自定义错误消息
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:
我的 .js 文件中只有这个:
$("#Form_Name").validationEngine();
Any help will be appreciated, I already have a few days trying to accomplish this...
任何帮助将不胜感激,我已经有几天时间尝试完成此任务...
采纳答案by Ian Stanway
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.
您需要做的就是修改 jquery.validationEngine-en.js 中的消息(如果不是英语,则可以使用任何您想要的语言)。请记住,您更改的验证类型的所有字段都将显示相同的消息。
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 iPragmaTechcame up with a solution for the same problem using the title attribute of the field.
\编辑 - 啊,我明白你的意思。好吧,我不能相信这一点,但是一家名为iPragmaTech的公司使用字段的标题属性为同一问题提出了解决方案。
They override buildprompt function from the validationengine and added functionality to pick the customized error message.
它们覆盖了验证引擎中的 buildprompt 功能,并添加了选择自定义错误消息的功能。
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.
我希望这能解决你的问题。
回答by khaled_webdev
回答by siby
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
这有效
<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" />
有关更多详细信息:参考
回答by mohan gathala
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
您可以设置自己的自定义错误消息。在这个脚本中,“required”已经在工作,现在我们要创建一个新规则“required_2”。第 1 步:在 jquery.validationEngine.js 文件中创建一个新案例
case "required_2":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;
Add add function for required_2
为 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 [email protected] for select boxes, Thank you
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "select-multiple":
// added by [email protected] 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
步骤: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"
},
Step:3 Now almost is done and you can use this in your html fields for example
步骤:3 现在差不多完成了,您可以在 html 字段中使用它,例如
<input value="" class="validate[required_2] text-input" type="text" name="req1" id="req1" data-prompt-position="topRight:-70" />
回答by Matthew Crosswell
**Try this.. works for me :) Modified the promtText if the title is set using the following code in jquery.validationEngine.js
**试试这个.. 对我有用:) 如果在 jquery.validationEngine.js 中使用以下代码设置标题,则修改 promtText
if (field.attr("title") != null) promptText = field.attr("title");
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);
}
},