[英]How to not submit a form if validation is false
How can I make sure the form won't submit if one of the validations is false?如果其中一项验证为假,我如何确保表单不会提交?
$('#form').submit(function(){
validateForm1();
validateForm(document.forms['dpart2']);
validateForm(document.forms['dpart3']);
});
$('#form').submit(function(){
return (validateForm1() &&
validateForm(document.forms['dpart2']) &&
validateForm(document.forms['dpart3']))
});
Basically, you return false in the event handler function.基本上,您在事件处理程序 function 中返回 false。
If the function returns false, form won't be submitted.如果 function 返回 false,则不会提交表单。
$('#form').submit(function(){
return validateForm1()
&& validateForm(document.forms['dpart2'])
&& validateForm(document.forms['dpart3']);
}
});
Okay, some of the other solutions will have a lazy fail... you probably want all your validation to run, so that all errors are displayed.好的,其他一些解决方案会出现延迟失败......您可能希望运行所有验证,以便显示所有错误。 The presumption is that your validation methods will return false if they fail.假设您的验证方法如果失败将返回 false。
$("#myform").submit(function() {
var ret = true;
ret = validateForm1() && ret;
ret = validateForm(document.forms['dpart2']) && ret
ret = validateForm(document.forms['dpart3'])) && ret
return ret;
});
This way all your validators will be called, but the Boolean value for any failure, will result in a fail.这样你所有的验证器都会被调用,但是任何失败的 Boolean 值都会导致失败。
If validateForm(...) and validateForm1() return a boolean (true means that no validation error occurred), then you try to do that:如果 validateForm(...) 和 validateForm1() 返回 boolean (true 表示没有发生验证错误),那么您尝试这样做:
$('#form').submit(function(){
if (!validateForm1() || !validateForm(document.forms['dpart2']) || !validateForm(document.forms['dpart3'])) {
return false;
}
});
A thought that comes up automatically: Even if you implemented thorough client side validation be prepared to receive any invalid request data on the server that you can possibly imagine.一个自动出现的想法:即使您实施了彻底的客户端验证,也要准备好在服务器上接收您可以想象的任何无效请求数据。
Client-side validation never keeps you from server-side validation.客户端验证永远不会让您远离服务器端验证。 It is just a bonus in usability.这只是可用性的一个奖励。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.