2016-12-12 34 views
0

我一直在嘗試使用JS OOP做表單驗證;我在Firefox和Chrome中測試了代碼:這兩個瀏覽器都被凍結了。無論投入是否符合規定的正則表達式,他們都沒有提交。那麼,誰知道我錯在哪裏?請問:我知道jQuery驗證器存在,我也可以使用普通的JS去儘可能的情況。在這裏,我的興趣是將JS OOP連接到DOM。我讀過的博客和教科書並沒有真正向我展示如何將jS OOP連接到DOM腳本。因此,我只是通過廢墟清理,尋找出路。此代碼對我的電池造成了損失,因此我決定在這裏分享。使用JavaScript面向對象的方法來驗證表單

<form method = 'post' action ='somewhere.com' onsubmit = 'return formApp.validateInputs.apply(formApp);'> 
<p> 
Name: <input type = 'text' name = 'userName' id = 'userName'> 
</p> 
<p> 
Phone: <input type = 'text' name = 'userPhone' id = 'userPhone'> 
</p> 
<input type = 'submit' id = 'sub' value = 'Submit Data'> 
</form> 
var formApp = { 
    userNameReg: /[a-z0-9 ' _ ]+/gi, 
    onlySpaceReg: /\s+/, 
    phoneReg: /\d{3}/, 
    userName: document.getElementById('userName').value, 
    userPhone: document.getElementById('userPhone').value, 
    error: [], 
    reportError: function() { 
     for (var i = 0; i < this.error.length; i++) { 
      alert(this.error[i] + '\n') 
     } 
    }, 
    validateInputs: function() { 
     if (!this.userNameReg.test(this.userName) || this.onlySpaceReg.test(this.userName)) { 
      this.error.push['Name contains illegal character']; 
      return false 
     } // end name validation 

     if (!this.phoneReg.test(this.userPhone)) { 
      this.error.push['Only a three-digit number']; 
      return false; 
     } // end phone validation 

     if (this.error.length > 0) { 
      this.reportError(); 
      return false; 
     } 

     return true; 
    } // end validateInputs 
}; // end formApp obj 
+0

爲什麼'formApp.validateInputs.apply(formApp);'?爲什麼申請? 調試器說什麼? – helle

+0

只是關於Javascript驗證的一個重要的FYI。不應該依賴它來確保用戶輸入有效。這很容易繞過(關閉javascript,使用諸如curl之類的非javascript客戶端)。如果你有基於javascript的驗證,它應該被認爲是一種可用性輔助而不是安全功能,並且輸入的實際驗證仍然必須在服務器端完成。 – GordonM

回答

0

其中的一個問題是,你將永遠不會得到一個警告,因爲你從功能返回所有的,如果在其中添加一個錯誤塊。所以「this.reportError();」永遠不能執行。從ifs中刪除「return false」語句。

validateInputs: function() { 
    if (!this.userNameReg.test(this.userName) || this.onlySpaceReg.test(this.userName)) { 
    this.error.push['Name contains illegal character']; 
    }// end name validation 
    if (!this.phoneReg.test(this.userPhone)) { 
    this.error.push['Only a three-digit number']; 
    }// end phone validation 
    if (this.error.length > 0) { 
    this.reportError(); 
    return false; 
    } 
    return true; 
}