看来,如果您的验证检查返回false,您可以阻止发送表单。Javascript - 如何防止表单发送多重验证检查?
我:在我的JavaScript
<form name="registration" action="registration.php" onsubmit="return validate()">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
我的validate()函数是由多个不同的检查虽然。
function validate() {
checkUsername();
checkPassword();
checkFirstname();
checkLastname();
checkBirthdate();
checkEmail();
checkPhone();
}
可能会出现用户输入除一个之外的全部有效数据的情况。如果是这样的话,我该如何告诉validate()仍然将“false”发送回表单,以便它不提交?
编辑:如果有人仍在阅读本文,出于某种原因,我的表单仍在发送。我甚至改变了我的validate()函数,所以唯一的声明是“return false;”我有语法错误还是什么?编辑2:我发现了另一种简单的解决方案,即使有点过时。它克服了我在函数仅评估第一个检查并返回的问题。
function validate() {
var truth1 = checkUsername();
var truth2 = checkPassword();
var truth3 = checkFirstname();
var truth4 = checkLastname();
var truth5 = checkBirthdate();
var truth6 = checkEmail();
var truth7 = checkPhone();
return (truth1 && truth3 && truth5 && truth2 && truth4 && truth6 && truth7);
}
尝试调用'event.preventDefault()'执行前归还检查。如果从所有检查调用返回'true',则在'form'元素上调用'.submit()' – guest271314
我会给它一个镜头,但是我认为有一个更简单的方法。我基于它的例子来自http://www.w3schools.com/js/js_validation.asp,它非常简单 –
@NicolasHassan最简单的方法可能是在每个类中使用'required'和'pattern'属性“形式”元素 – guest271314