使用 jQuery Unobtrusive Validation 时如何添加“submitHandler”函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4747017/
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 add a 'submitHandler' function when using jQuery Unobtrusive Validation?
提问by WooWaaBob
I'm validating a form using the new unobtrusive validation features in ASP.NET MVC 3.
我正在使用 ASP.NET MVC 3 中新的不显眼的验证功能验证表单。
So there is no code that I have written to setup jQuery validate to start validating my form. Its all done by loading the jQuery.validate.unobtrusive.js library.
所以我没有编写代码来设置 jQuery 验证以开始验证我的表单。这一切都是通过加载 jQuery.validate.unobtrusive.js 库来完成的。
Unfortunately I need to whack in a 'are you sure?' message box when the form is valid but before submitting. With jQuery validate you would add the option handleSubmit when initialising like so:
不幸的是,我需要回答“你确定吗?” 表单有效但提交前的消息框。使用 jQuery 验证,您将在初始化时添加选项 handleSubmit,如下所示:
$("#my_form").validate({
rules: {
field1: "required",
field1: {email: true },
field2: "required"
},
submitHandler: function(form) {
if(confirm('Are you sure?')) {
form.submit();
}
}
});
But you don't need to initialise when using the unobtrusive library.
但是在使用不显眼的库时不需要初始化。
Any ideas where/how I can add a submit handler in that case?
在这种情况下,我可以在哪里/如何添加提交处理程序的任何想法?
Thx
谢谢
回答by petrhaus
The unobtrusive library will attach the validator on all forms, so you have to replace the submitHandler this way:
不显眼的库将在所有表单上附加验证器,因此您必须以这种方式替换 submitHandler:
$("form").data("validator").settings.submitHandler = function (form) { alert('submit'); form.submit(); };
回答by DGreen
I found this question while looking for a way to set the invalidHandler
, as opposed to the submitHandler
. Interestingly, you can't set invalidHandler
in the same way when using unobtrusive validation.
我在寻找设置.invalidHandler
而不是submitHandler
. 有趣的是,invalidHandler
在使用不显眼的验证时,您不能以相同的方式进行设置。
The function is not fired when an invalid form is detected:
当检测到无效表单时,不会触发该函数:
$("form").data("validator").settings.invalidHandler = function (form, validator) {
alert('invalid!');
};
This approach works:
这种方法有效:
$("form").bind("invalid-form.validate", function () {
alert('invalid!');
});
It seems to be due to the way that the jquery.validate.unobtrusive.jsscript initialises the Validateplugin, and the way that the plugin invokes the handler.
这似乎是由于jquery.validate.unobtrusive.js脚本初始化Validate插件的方式,以及插件调用处理程序的方式。
回答by Simon_Weaver
The following findings may be of interest to understand the difference between :
以下发现可能有助于理解 之间的差异:
submitHandler: Called when the form is validated successfully - right before the server postback
invalidHandler: Called if validation fails and there is no post back
submitHandler:当表单验证成功时调用 - 就在服务器回
发之前invalidHandler:如果验证失败并且没有回发则调用
@DGreen's solution definitely seems to be the best way to inject special handling if the form validation fails and you need to do something such as display a pop-up validation summary (invalidHandler)
如果表单验证失败并且您需要执行诸如显示弹出验证摘要(invalidHandler)之类的操作,@DGreen 的解决方案绝对似乎是注入特殊处理的最佳方法
$("form").bind("invalid-form.validate", function () {
alert('invalid!');
});
@PeteHaus solution is the best way to do something if you want to prevent postback of a successfully validated form (submitHandler)
如果您想阻止成功验证的表单(submitHandler)的回发,@PeteHaus 解决方案是做某事的最佳方式
$("form").data("validator").settings.submitHandler = function (form) {
alert('submit'); form.submit(); };
However I was slightly concerned about what behavior I was overriding (or not overriding) by binding to the .validate
method like this - and why I had to do each way differently. So I checked the source. I strongly recommend anybody who wants to understand this procedure more does so too - put in some 'alert' statements or 'debugger' statements and it's pretty easy to follow along*
然而,我有点担心我通过绑定到这样的.validate
方法来覆盖(或不覆盖)什么行为- 以及为什么我必须以不同的方式做每一种。于是我查了一下源码。我强烈建议任何想要更多地了解此过程的人也这样做 - 放入一些“警报”语句或“调试器”语句,并且很容易遵循*
Anyway it turns out that when the jquery.validate.unobtrusive
handler initializes jquery.validate
plugin it does so in the parseElement()
method by retrieving options created by the validationInfo()
method.
无论如何,事实证明,当jquery.validate.unobtrusive
处理程序初始化jquery.validate
插件时,它parseElement()
通过检索方法创建的选项在validationInfo()
方法中这样做。
ValidationInfo()
returns the options like this:
ValidationInfo()
返回这样的选项:
options: { // options structure passed to jQuery Validate's validate() method
errorClass: "input-validation-error",
errorElement: "span",
errorPlacement: $.proxy(onError, form),
invalidHandler: $.proxy(onErrors, form),
messages: {},
rules: {},
success: $.proxy(onSuccess, form)
},
The onErrors()
method in jquery.validate.unobtrusive
is responsible for dynamically creating the validation summary panel for MVC. If you're not creating a validation summary panel (with @Html.ValidationSummary()
which must incidentally be contained within the FORM body) then this method is completely inert and does nothing so you don't need to worry.
的onErrors()
在方法jquery.validate.unobtrusive
负责动态创建用于MVC验证摘要面板。如果您不创建验证摘要面板(@Html.ValidationSummary()
必须附带包含在 FORM 主体中),那么此方法是完全惰性的并且什么都不做,因此您无需担心。
function onErrors(event, validator) { // 'this' is the form elementz
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
If you really want to you can unbind the jquery.validate.unobtrusive
handler like this - but i wouldn't bother myself
如果你真的想要,你可以jquery.validate.unobtrusive
像这样解除绑定处理程序 - 但我不会打扰自己
$("form").unbind("invalid-form.validate"); // unbind default MS handler
If you're wondering why this works
如果你想知道为什么这有效
$("form").data("validator").settings.submitHandler = ...
and this doesn't work
这不起作用
$("form").data("validator").settings.invalidHandler = ...
it's because submitHandler
is explicily called inside jquery.validate
when validation is performed. Therefore it doesn't matter at what point it is set.
这是因为submitHandler
在jquery.validate
执行验证时在内部显式调用。因此,在什么时候设置它并不重要。
validator.settings.submitHandler.call( validator, validator.currentForm );
but the invalidHandler
is bound to an event during init()
like this so if you set it in your own code it is too late
但是在这样的invalidHandler
过程中绑定到一个事件init()
所以如果你在你自己的代码中设置它为时已晚
if (this.settings.invalidHandler)
$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
A little stepping through code makes for a lot of understanding sometimes! Hope this helps
对代码进行一点点单步调试有时会带来很多理解!希望这可以帮助
*Make sure you don't have minification in bundles enabled.
*确保您没有启用捆绑包中的缩小。
回答by Tracker1
I prefer to inject an event handler, so that it can be bound to... :)
我更喜欢注入一个事件处理程序,以便它可以绑定到... :)
//somewhere in your global scripts
$("form").data("validator").settings.submitHandler = function (form) {
var ret = $(form).trigger('before-submit');
if (ret !== false) form.submit();
};
This way, I can bind to it anywhere needed...
这样,我可以在任何需要的地方绑定它......
//in your view script(s)
$("form").bind("before-submit", function() {
return confirm("Are you sure?");
});
回答by Andrew Backer
I based this on the original answer, which didn't work for me. I guess things have changed in jQuery.
我基于原来的答案,这对我不起作用。我想事情在 jQuery 中发生了变化。
As usual, take this code and add copious error checking :D I use similar code to prevent double-submits on our forms, and it works fine in IE8+ (as of mvc4 and jquery 1.8.x).
像往常一样,使用此代码并添加大量错误检查:DI 使用类似的代码来防止我们的表单上的重复提交,并且它在 IE8+ 中运行良好(从 mvc4 和 jquery 1.8.x 开始)。
$("#myFormId").confirmAfterValidation();
// placed outside of a $(function(){ scope
jQuery.fn.confirmAfterValidation = function () {
// do error checking first. should be null if no handler already
$(this).data('validator').settings.submitHandler = confirmValidForm;
};
function confirmValidForm(form) {
var validator = $(this);
var f = $(form);
if (confirm("really really submit?")) {
// unbind so our handler doesn't get called again, and submit
f.unbind('submit').submit();
}
// return value is _ignored_ by jquery.validate, so we have to set
// the flag on the validator itself, but it should cancel the submit
// anyway if we have a submitHandler
validator.cancelSubmit = true;
}
}