如何有条件地执行jQuery validate插件 [英] How to conditionally execute jQuery validate plugin
问题描述
我有一个正在通过jQuery validate插件验证的表单(类似于下图)-
I have a form (similar to shown below) which is being validated by jQuery validate plugin -
$("#form").validate({
debug: true,
rules: {
Field1: {
required: true,
field1condition: true
},
Field2: {
required: true,
field2condition: true
}
}
,
submitHandler: function (form) {
submit(form)
}
});
仅当某些按钮(例如id="clickme"
)早些时候被单击时,我才需要验证整个表单.但无论如何,都应提交表单(因此,如果单击了按钮,然后进行验证并提交,否则将不运行验证而仅提交).我可以为每个字段使用depends:
,但是这似乎很麻烦,因为我对每个字段都有很多条件.有没有更简单的方法来实现此功能?
I need this entire form to be validated ONLY if certain button (let's say id="clickme"
) has been clicked earlier. But in any case, the form should be submitted (so if the button was clicked then validate and submit else don't run validate and only submit). I can use depends:
for each field but it seems like a cumbersome task as I have a lot of conditions for every field. Is there any simpler way to achieve this functionality?
谢谢.
推荐答案
(因此,如果单击了该按钮,则进行验证并提交,否则不运行验证并仅提交)是否有更简单的方法来实现此功能?
(so if the button was clicked then validate and submit else don't run validate and only submit) Is there any simpler way to achieve this functionality?
是.
使用submit
按钮上的class="cancel"
.
<input type="submit" class="cancel" ....
或
<button type="submit" class="cancel" ....
使用class="cancel"
,此按钮将按照插件的submitHandler
提交表单,并完全绕过表单验证.如果没有class="cancel"
,则此按钮将触发验证,并且仅在表单完全验证后才提交.
Using class="cancel"
, this button will submit the form as per the plugin's submitHandler
and bypass the form validation entirely. Without class="cancel"
, this button would trigger validation and only submit when the form is fully validated.
我想您可以基于其他操作,功能或按钮,在单个表单submit
按钮上动态添加/删除此cancel
类.
I suppose you could dynamically add/remove this cancel
class on a single form submit
button based on some other action, function or button.
顺便说一句:
您的submitHandler
可能是多余的...
Your submitHandler
is probably superfluous...
submitHandler: function (form) {
submit(form)
}
我只说大概"是因为我不确定您是否还有另一个名为submit()
的函数,或者您是否只是在不正确地使用jQuery .submit()
.
I only say "probably" because I'm not sure if you have another function named submit()
or if you're simply improperly using jQuery .submit()
.
但是,这更像是插件默认情况下所做的...
However, this is more like what the plugin is doing by default...
submitHandler: function (form) {
$(form).submit(); // <- default form action
}
如果是这种情况,那么您甚至不需要submitHandler
选项,因为这已经是插件的默认行为.只需删除submitHandler
.
If that's the case, then you do not even need the submitHandler
option, since that is already the default behavior of the plugin. Simply remove the submitHandler
.
这篇关于如何有条件地执行jQuery validate插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!