2013-05-20 183 views
0

我遇到了簡單的密碼驗證問題。JavaScript驗證密碼錯誤

這些都是事情驗證確實

  • 檢查,如果密碼少於8個字符
  • 檢查,如果是超過15個字符
  • 檢查是否有新的密碼,並重新輸入不匹配

表格提交兩個密碼匹配時即使小於或大於驗證

請看看我的代碼:

function on_submit(dest) { 

    var objForm = document.LogonForm; 
    var strMissingInfo = ""; 

    if (dest == 'logon') { 

     if (objForm.current.value != "") { 

      if (objForm.new1.value.length < 8 || objForm.new1.value.length > 15) { 
       strMissingInfo += "\n Password must be 8 to 15 characters long"; 

      } else if (objForm.retype.value != objForm.new1.value) { 
       strMissingInfo += "\n Password mismatch!"; 

      } 

      if (strMissingInfo != "") { 
       alert(strMissingInfo); 

      } else { 
       alert(strMissingInfo); 
       objForm.action.value = dest; 
       objForm.submit(); 
      } 
     } 
    } 
} 

--- HTML部分

<input type="password" id="current" name="current" 
           onKeyPress="return isNumberKey(event)" style="width: 180px" 
           tabindex="1" required/> 

<input type="password" id="new1" name="new1" 
           onKeyPress="return isNumberKey(event)" style="width: 180px" 
           tabindex="2" required /> 

<input type="password" id="retype" name="retype" 
           onKeyPress="return isNumberKey(event)" style="width: 180px" 
           tabindex="3" required /> 

<a href="javascript:;"> 
        <input id="logonButton" class="submit" 
         type="submit" name="Submit" value="Confirm" tabindex="4" 
         onclick="on_submit('logon')" /> 
        </a> 
+3

只是出於好奇,你爲什麼要施加15個字符的上限? – Blender

+0

如果您在表單中使用按鈕,無論您使用Javascript做什麼,它都會默認提交。你能告訴我們這個函數是如何被調用的嗎?此外,你最初檢查'current.value'然後切換到'new1.value'這是故意的嗎? –

+0

我其實有三個字段。 1.當前密碼2.新密碼3.重新輸入密碼。 –

回答

0

既然你不提警報發生的歷史,我的猜測是,你是調用此函數的一個按鈕從表格內。這將自動提交表單,而不管的onclick功能,除非你設置按鈕上的類型,在這個問題描述:如果你希望表單未能在提交嘗試驗證失敗時返回false How to prevent buttons from submitting forms

<input id="logonButton" class="submit" 
        type="button" name="Submit" value="Confirm" tabindex="3" 
        onclick="on_submit('logon')" /> 
+0

是的我打電話onClick提交按鈕的功能。謝謝,, –

+0

好吧,那麼你將需要添加type =按鈕到該按鈕的標記。否則它會自動提交表單。你的功能可能工作也可能不工作,難以確定,因爲我不知道你的變量是什麼,但它現在甚至沒有運行:) –

+0

即使驗證滿足,它也不會提交。 –

0

 if (strMissingInfo != "") { 
      alert(strMissingInfo); 
      return false; 
     } 
+0

我試過了。並且錯誤仍然是相同的 –

+0

你可以通過你的LogonForm標記 – lfender6445

0

您需要返回要麼true(提交表單),從功能的必要或false(停止提交),並且還使用onclick="return on_submit('logon');" - 甚至更好,你應該將其刪除,並把onsubmit="return on_submit('logon');"形式本身。

+0

在我的功能區,它是否必須返回任何東西? –

+0

嘿,錯誤仍然是一樣的。我試了兩次,onClick和onSubmit返回.. –

+0

錯誤仍然是一樣的。即使密碼小於8或大於15,表單也會提交。 –