Javascript 如果验证失败如何停止表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35487417/
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 stop Form submit if the validation fails
提问by Nick Kahn
UPDATE:
my question is more about How to prevent the form submit if the validation fails
更新:我的问题更多是关于 How to prevent the form submit if the validation fails
the link does not solve my problem
该链接不能解决我的问题
just re-iterate what I'm doing:
I have a form with bunch of input fields and when the user hit the submit button it validate form using attribute required="required"
if the form validation fails THEN I want to stop submitting the form as you see the javascript it show the div when the user submit the form.
只需重复我正在做的事情:我有一个带有一堆输入字段的表单,当用户点击提交按钮时,required="required"
如果表单验证失败,它会使用属性验证表单然后我想在您看到 javascript 时停止提交表单它在用户提交表单时显示 div。
Hope this clears up.
希望这能澄清。
END UPDATE
结束更新
How can I stop the form submit to fire if the form validation fails?
如果表单验证失败,如何阻止表单提交触发?
<input class="form-control" data-val="true" id="SerialNumber" name="SerialNumber" required="required" type="text">
<button type="submit" name="rsubmit" class="btn btn-success">Submit</button>
//loading message:
$("form").submit(function (e) {
$("#loading").show();
});
采纳答案by Nick Kahn
I able to fixed the problem:
我能够解决这个问题:
First add the ref on your page:
首先在您的页面上添加引用:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
then do this check:
然后做这个检查:
$("form").submit(function () {
if ($(this).valid()) { //<<< I was missing this check
$("#loading").show();
}
});
回答by Farside
You need to do two things if validation fails, e.preventDefault() and to return false.
如果验证失败,您需要做两件事,e.preventDefault() 和返回 false。
For your example, with the input given, the pseudo code might be the next:
对于您的示例,在给定输入的情况下,伪代码可能是下一个:
$("form").submit(function (e) {
var validationFailed = false;
// do your validation here ...
if (validationFailed) {
e.preventDefault();
return false;
}
});
回答by Cheezy Code
Write your validation code on onsubmit handler of your form like this
像这样在表单的 onsubmit 处理程序上编写验证代码
<form onsubmit="return Validation()">
<input class="form-control" data-val="true" id="SerialNumber" name="SerialNumber" required="required" type="text">
<button type="submit" name="rsubmit" class="btn btn-success">Submit</button>
<script>
function Validation(){
//Do all your validation here
//Return true if validation is successful, false if not successful
//It will not submit in case of false.
return true or false;
}
</script>
</form>