我已經寫了一個函數,應該防止任何東西被提交,除非兩個條件是真實的 - 即該值已被放入每個所需的類別中,並且如果每個類別中都有值,那麼有效的電話號碼已提交。表單提交通過
相反,現在發生的事情是我會得到錯誤消息,但是它會提交表單。我在代碼中看不到錯誤,你能看到什麼嗎?
function formValidation() {
var ids = ["orgname", "cultpicklist", "catpicklist", "servpicklist", "phone", "add1", "url", "state"] // required fields
formValue = 1; // value indicating whether to go to the next step of the process, phone number validation. On by default.
if (document.getElementById('deletebutton') != null && document.getElementById('orgname').value === "") {
formValue = 0; // A separate test for when the delete button is clicked.
}
else {
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0; // Testing each of the list items
break;
}
}
}
// Here's the part where, if everything else passes checks, we have a regex test for phone number validation
if (formValue == 1) {
phoneVal = document.getElementById("phone");
if (/^\d{3}-\d{3}-\d{4}$/.test(phoneVal) || /^\d{10}$/.test(phoneVal) || /^\(\d{3}\) \d{3}-\d{4}$/.test(phoneVal)) {
return true;
}
else {
alert("Please put in a correct phone number");
return false;
// This shouldn't submit, but does.
}}
else if (formValue == 0) {
alert('Please fill out all required fields');
return false;
// This also shouldn't submit, but does as well.
}
}
可以粘貼你在哪裏調用這個函數HTML部分。它應該有onSubmit =「return formValidation()」 – Pradeep
這個函數本身看起來很好乍一看。你打電話過得怎麼樣?我認爲它需要來自「提交」處理程序才能停止表單提交。 –
我錯過了一些上下文。你在哪裏調用這個函數?的onsubmit? – Iljaas