看來,如果您的驗證檢查返回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