如何仅在表单有效时才触发 jQuery 函数
我有一个与提交按钮绑定的 jQuery 函数,如下所示:
$(function () {
$('#signupform').submit(function () {
alert('test');
});
});
但是,无论表单是否有效,它都会触发。我的模型用各种 DataAnnotations 装饰,并且客户端验证运行良好,但我只希望在表单已验证时触发 jQuery 函数。我该如何做到这一点?
编辑:澄清一下,我使用 MVC DataAnnotations + jQuery 的不显眼的 javascript 来处理客户端验证。我没有编写自己的 javascript 验证例程。内置的 jQuery 验证在验证表单方面做得很好,但我只需要知道如何将该验证的结果转换为我自己的函数中的布尔值。
I have a jQuery function tied to my submit button like this:
$(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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 jquery validate 不引人注目的验证,您可以:
If you are using jquery validate unobtrusive validation you could:
请注意,
validateForm()
函数将是您在浏览器中用于测试验证的函数。编辑:这确实是 jQuery 的$(this).valid()
。注意:在澄清问题时,上面的答案是停止验证时提交表单的一种方法,但不是所需的技术(jQuery 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()
.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.
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.