jquery 验证:防止表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10305938/
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: prevent form submit
提问by alex
By the use of the jQuery plugin Validation, I am trying to, well, validate my form. When the validation passes, I want a javascript to fire with values from the form and then stop. no actual form submission with browsing to a new/same site.
通过使用 jQuery 插件验证,我正在尝试验证我的表单。当验证通过时,我希望 javascript 使用表单中的值触发,然后停止。没有实际的表单提交浏览到一个新的/相同的网站。
is this possible with jquery validation?
这可以通过 jquery 验证实现吗?
回答by The Alpha
You may try this (Example):
你可以试试这个(例子):
$(function(){
$("#myform").validate();
$("#myform").on('submit', function(e) {
var isvalid = $("#myform").valid();
if (isvalid) {
e.preventDefault();
alert(getvalues("myform"));
}
});
});
function getvalues(f)
{
var form=$("#"+f);
var str='';
$("input:not('input:submit')", form).each(function(i){
str+='\n'+$(this).prop('name')+': '+$(this).val();
});
return str;
}
回答by undefined
Yes:
是的:
$("form").submit(function(event) {
if (somethingIsInvalid) {
event.preventDefault();
}
});
回答by que1326
$("#form").validate({
rules: {...},
submitHandler: function(form, event) {
event.preventDefault();
alert("Do some stuff...");
//submit via ajax
}
});
回答by Jorge
There's a method called .valid() which return true in case the there's no errors in you form, so you can validate first with this and then send the form here's the documentation
有一个名为 .valid() 的方法,如果表单中没有错误,它会返回 true,因此您可以先使用此方法进行验证,然后将表单发送至此处的文档