jQuery 验证插件:禁用指定提交按钮的验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/203844/
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
jQuery Validation plugin: disable validation for specified submit buttons
提问by Ted
I have a form with multiple fields that I'm validating (some with methods added for custom validation) with J?rn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.
我有一个包含多个字段的表单,我正在使用 J?rn Zaeffere 出色的 jQuery 验证插件进行验证(有些添加了用于自定义验证的方法)。您如何绕过指定提交控件的验证(换句话说,使用某些提交输入进行验证,但不使用其他输入进行验证)?这将类似于具有标准 ASP.NET 验证器控件的 ValidationGroups。
My situation:
我的情况:
It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?
它与 ASP.NET WebForms 一起使用,但如果您愿意,可以忽略它。但是,我更多地将验证用作“建议”:换句话说,当提交表单时,验证会触发,但不是“必需”消息显示,而是“建议”显示,它说的是“你错过了以下字段.... 你还想继续吗?” 在错误容器中的那个点上,现在可以看到另一个提交按钮,可以按下它会忽略验证并提交。如何绕过此按钮控件的表单 .validate() 并仍然发布?
The Buy and Sell a House sample at http://jquery.bassistance.de/validate/demo/multipart/allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.
http://jquery.bassistance.de/validate/demo/multipart/ 上的 Buy and Sell a House 示例允许这样做以访问前面的链接,但它是通过创建自定义方法并将其添加到验证器来实现的。我宁愿不必创建自定义方法来复制验证插件中已有的功能。
The following is a shortened version of the immediately applicable script that I've got right now:
以下是我现在得到的立即适用脚本的缩短版本:
var container = $("#<%= Form.ClientID %> div.validationSuggestion");
$('#<%= Form.ClientID %>').validate({
errorContainer: container,
errorLabelContainer: $("ul",container),
rules: {
<%= YesNo.UniqueID %>: { required: true },
<%= ShortText.UniqueID %>: { required: true } // etc.
},
messages: {
<%= YesNo.UniqueID %>: 'A message.',
<%= ShortText.UniqueID %>: 'Another message.' // etc.
},
highlight: function(element, errorClass) {
$(element).addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").removeClass("valid");
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").addClass("valid");
},
wrapper: 'li'
});
回答by redsquare
You can add a CSS class of cancel
to a submit button to suppress the validation
您可以cancel
向提交按钮添加一个 CSS 类以取消验证
e.g
例如
<input class="cancel" type="submit" value="Save" />
See the jQuery Validator documentation of this feature here: Skipping validation on submit
请在此处查看此功能的 jQuery 验证器文档:提交时跳过验证
EDIT:
编辑:
The above technique has been deprecated and replaced with the formnovalidate
attribute.
上述技术已被弃用并替换为formnovalidate
属性。
<input formnovalidate="formnovalidate" type="submit" value="Save" />
回答by lepe
Other (undocumented) way to do it, is to call:
其他(未记录的)方法是调用:
$("form").validate().cancelSubmit = true;
on the click event of the button (for example).
在按钮的点击事件上(例如)。
回答by Daniel Garcia
Yet another (dynamic) way:
另一种(动态)方式:
$("form").validate().settings.ignore = "*";
And to re-enable it, we just set back the default value:
要重新启用它,我们只需设置回默认值:
$("form").validate().settings.ignore = ":hidden";
Source: https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443
来源:https: //github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443
回答by TastyCode
Add formnovalidate attribute to input
将 formnovalidate 属性添加到输入
<input type="submit" name="go" value="Submit">
<input type="submit" formnovalidate name="cancel" value="Cancel">
Adding class="cancel" is now deprecated
添加 class="cancel" 现在已弃用
See docs for Skipping validation on submit on this link
请参阅此链接上提交时跳过验证的文档
回答by BrokeMyLegBiking
You can use the onsubmit:falseoption (see documentation) when wiring up validation which will not validate on submission of the form. And then in your asp:button add an OnClientClick= $('#aspnetForm').valid(); to explicitly check if form is valid.
您可以在连接验证时使用onsubmit:false选项(请参阅文档),这不会在提交表单时进行验证。然后在你的 asp:button 添加一个 OnClientClick= $('#aspnetForm').valid(); 明确检查表单是否有效。
You could call this the opt-in model, instead of the opt-out described above.
您可以将其称为选择加入模型,而不是上述选择退出模型。
Note, I am also using jquery validation with ASP.NET WebForms. There are some issues to navigate but once you get through them, the user experience is very good.
请注意,我还在 ASP.NET WebForms 中使用了 jquery 验证。有一些问题需要解决,但是一旦您解决了这些问题,用户体验就会非常好。
回答by Simon_Weaver
(Extension of @lepe
's and @redsquare
answer for ASP.NET MVC
+ jquery.validate.unobtrusive.js
)
(@lepe
's 的扩展和+ 的@redsquare
答案)ASP.NET MVC
jquery.validate.unobtrusive.js
The jquery validation plugin(not the Microsoft unobtrusive one) allows you to put a .cancel
class on your submit button to bypass validation completely (as shown in accepted answer).
在jQuery验证插件(不是微软不显眼的一个),可以把.cancel
你的提交按钮类绕过验证完全(如图接受的答案)。
To skip validation while still using a submit-button, add a class="cancel" to that input.
<input type="submit" name="submit" value="Submit"/>
<input type="submit" class="cancel" name="cancel" value="Cancel"/>
(don't confuse this with type='reset'
which is something completely different)
(不要将此与type='reset'
完全不同的东西混淆)
Unfortunately the jquery.validation.unobtrusive.js
validation handling (ASP.NET MVC) code kinda screws up the jquery.validate plugin's default behavior.
不幸的是,jquery.validation.unobtrusive.js
验证处理 (ASP.NET MVC) 代码有点搞砸了jquery.validate 插件的默认行为。
This is what I came up with to allow you to put .cancel
on the submit button as shown above. If Microsoft ever 'fixes' this then you can just remvoe this code.
这就是我想出的方法,让您可以放置.cancel
如上所示的提交按钮。如果 Microsoft 曾经“修复”了这个问题,那么您可以删除此代码。
// restore behavior of .cancel from jquery validate to allow submit button
// to automatically bypass all jquery validation
$(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)
{
// find parent form, cancel validation and submit it
// cancelSubmit just prevents jQuery validation from kicking in
$(this).closest('form').data("validator").cancelSubmit = true;
$(this).closest('form').submit();
return false;
});
Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and seeing a server generated page with errors. You'll need to bypass validation on the server side by some other means - this just allows the form to be submitted client side without errors (the alternative would be adding .ignore
attributes to everything in your form).
注意:如果第一次尝试似乎这不起作用 - 确保您没有往返服务器并看到服务器生成的页面有错误。您需要通过其他方式绕过服务器端的验证 - 这只是允许表单在客户端无错误地提交(另一种方法是向.ignore
表单中的所有内容添加属性)。
(Note: you may need to add button
to the selector if you're using buttons to submit)
(注意:button
如果您使用按钮提交,则可能需要添加到选择器中)
回答by Davide Ciarmiello
$("form").validate().settings.ignore = "*";
Or
或者
$("form").validate().cancelSubmit = true;
But without success in a custom required validator. For call a submit dynamically, i have created a fake hidden submit button with this code:
但是在自定义所需的验证器中没有成功。为了动态调用提交,我使用以下代码创建了一个假的隐藏提交按钮:
var btn = form.children('input.cancel.fakeSubmitFormButton');
if (btn.length === 0) {
btn = $('<input name="FakeCancelSubmitButton" class="cancel fakeSubmitFormButton hide" type="submit" formnovalidate value="FakeCancelSubmitButton" />');
form.append(btn);
}
btn.click();
Now skip the validation correctly :)
现在正确跳过验证:)
回答by bradlis7
This question is old, but I found another way around it is to use $('#formId')[0].submit()
, which gets the dom element instead of the jQuery object, thus bypassing any validation hooks. This button submits the parent form that contains the input.
这个问题很老了,但我发现另一种解决方法是使用$('#formId')[0].submit()
,它获取 dom 元素而不是 jQuery 对象,从而绕过任何验证挂钩。此按钮提交包含输入的父表单。
<input type='button' value='SubmitWithoutValidation' onclick='$(this).closest('form')[0].submit()'/>
Also, make sure you don't have any input
's named "submit", or it overrides the function named submit
.
此外,请确保您没有任何input
名为“提交”的文件,否则它会覆盖名为submit
.
回答by Scott Mayers
I found that the most flexible way is to do use JQuery's:
我发现最灵活的方法是使用 JQuery 的:
event.preventDefault():
E.g. if instead of submitting I want to redirect, I can do:
例如,如果我想重定向而不是提交,我可以这样做:
$("#redirectButton").click(function( event ) {
event.preventDefault();
window.location.href='http://www.skip-submit.com';
});
or I can send the data to a different endpoint (e.g. if I want to change the action):
或者我可以将数据发送到不同的端点(例如,如果我想更改操作):
$("#saveButton").click(function( event ) {
event.preventDefault();
var postData = $('#myForm').serialize();
var jqxhr = $.post('http://www.another-end-point.com', postData ,function() {
}).done(function() {
alert("Data sent!");
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("Ooops, we have an error");
})
Once you do 'event.preventDefault();' you bypass validation.
一旦你做了'event.preventDefault();' 你绕过验证。
回答by Bugfixer
I have two button for form submission, button named save and exit bypasses the validation :
我有两个表单提交按钮,名为保存和退出的按钮绕过验证:
$('.save_exist').on('click', function (event) {
$('#MyformID').removeData('validator');
$('.form-control').removeClass('error');
$('.form-control').removeClass('required');
$("#loanApplication").validate().cancelSubmit = true;
$('#loanApplication').submit();
event.preventDefault();
});