Javascript 仅当表单有效时如何触发 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5052315/
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 fire jQuery function only if form is valid
提问by Scott
I have a jQuery function tied to my submit button like this:
我有一个与提交按钮相关的 jQuery 函数,如下所示:
$(function () {
$('#signupform').submit(function () {
alert('test');
});
});
However, it fires whether or not the form is valid. My model is decorated with various DataAnnotations and the client-side validation is working well, but I only want that jQuery function to fire if the form has been validated. How do I accomplish that?
但是,无论表单是否有效,它都会触发。我的模型装饰有各种 DataAnnotations 并且客户端验证运行良好,但我只希望在表单已验证时触发 jQuery 函数。我如何做到这一点?
EDIT:To clarify, I'm using MVC DataAnnotations + jQuery's unobtrusive javascript to handle the client-side validation. I do not have my own javascript validation routines written. The built in jQuery validation is doing a great job of validating the form, but I just need to know how to get the results of that validation into a boolean value within my own function.
编辑:澄清一下,我正在使用 MVC DataAnnotations + jQuery 的不显眼的 javascript 来处理客户端验证。我没有编写自己的 javascript 验证例程。内置的 jQuery 验证在验证表单方面做得很好,但我只需要知道如何在我自己的函数中将该验证的结果转换为布尔值。
回答by Darin Dimitrov
If you are using jquery validate unobtrusive validation you could:
如果您使用 jquery 验证不显眼的验证,您可以:
$(function () {
$('#signupform').submit(function () {
if($(this).valid()) {
alert('the form is valid');
}
});
});
回答by Jared Farrish
$(function () {
$('#signupform').submit(function (e) {
if (validateForm() === true) {
alert('Form is valid.');
}
});
});
Note, the validateForm()
function would be the one you use within the browser to test validation. EDIT: This is indeed jQuery's $(this).valid()
.
请注意,该validateForm()
函数将是您在浏览器中用于测试验证的函数。编辑:这确实是 jQuery 的$(this).valid()
.
NOTE: On clarification of the question, the answer above is one way to stop form submitting on validation, but not the technique that was desired (jQuery valid() validation). See Darin Dimitrov's answer for details.
注意:在澄清问题时,上面的答案是在验证时停止表单提交的一种方法,但不是所需的技术(jQuery valid() 验证)。有关详细信息,请参阅 Darin Dimitrov 的回答。
Also, on rereading the original question, the intent was the exact opposite of what I originally described. So I edited to demonstrate a functional response on validation, not how to prevent submitting a form.
此外,在重新阅读原始问题时,其意图与我最初描述的完全相反。所以我编辑来演示验证的功能响应,而不是如何阻止提交表单。