2011-12-06 188 views
0

我已經寫了一個函數,應該防止任何東西被提交,除非兩個條件是真實的 - 即該值已被放入每個所需的類別中,並且如果每個類別中都有值,那麼有效的電話號碼已提交。表單提交通過

相反,現在發生的事情是我會得到錯誤消息,但是它會提交表單。我在代碼中看不到錯誤,你能看到什麼嗎?

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. 
     } 


} 
+0

可以粘貼你在哪裏調用這個函數HTML部分。它應該有onSubmit =「return formValidation()」 – Pradeep

+0

這個函數本身看起來很好乍一看。你打電話過得怎麼樣?我認爲它需要來自「提交」處理程序才能停止表單提交。 –

+0

我錯過了一些上下文。你在哪裏調用這個函數?的onsubmit? – Iljaas

回答

1

我假設在你的HTML,你有這樣的事情

<form .... onsubmit="formValidation()"> 

應該

<form .... onsubmit="return formValidation()"> 
+0

這似乎適用於表單提交。不過需要使用我的正則表達式! –

+0

@Andrew正則表達式有什麼問題?它目前處理'123-456-7890','1234567890'和最後'(123)456-7890'。 –

+0

爲什麼需要「返回」? – Navigatron

0

這是函數從提交按鈕叫什麼?

提交按鈕將提交表單,無論JavaScript告訴它做什麼。考慮使用普通的舊按鈕並使用表單的submit()函數。

http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
    <body> 
     <form name="form" action="no.html"> 
      <input type="button" value="submit" onmousedown="dontSub()" /> 
     </form> 
    </body> 
    <script> 
     function dontSub() { 
      var good = false; 
      if(good) { 
       document.forms["form"].submit(); 
      } 
     } 
     </script> 
</html>