2016-04-04 46 views
2

在使用打字稿的HTML應用程序中,我有一個HTML表單。該表格有一些必填字段。在我的打字稿文件我建立一個錯誤信息是這樣的:所需字段的較短驗證功能

hasErrors() { 
    let errorCount = 0; 

    if (!item.Field1()) { 
     this.ErrorText('"Field1"'); 
     errorCount++; 
    } 
    if (!item.Field2()) { 
     if (errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "Field2"'); 
     else 
      this.ErrorText('"Field2"'); 
     errorCount++; 
    } 
    if (!item.Field3()) { 
     if (errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "Field3"'); 
     else 
      this.ErrorText('"Field3"'); 
     errorCount++; 
    } 

    // ... 

    if (errorCount > 1) 
     this.ErrorText("The fields " + this.ErrorText() + " are required."; 
    else if (errorCount == 1) 
     this.ErrorText("The field " + this.ErrorText() + " is required."; 
    else 
     return false; 
    return true; 
} 

正如你可以看到,這個功能會非常長,如果有需要,許多領域。有沒有更好/更短的方式來獲得相同的結果?

回答

1
function catErrors(field){ 
    if (!item.field) { 
     if (this.errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "' + field + '"'); 
     else 
      this.ErrorText('"' + field + '"'); 
     this.errorCount++; 
    } 
} 

你可能創建一個函數來尋找錯誤嗎? 你可以這樣調用函數:catErrors(Field1)
這將有助於縮短您的代碼。您只需手動添加第一個字段即可開始,隨後的所有內容都將使用功能catErrors()。希望這可以幫助!

+0

謝謝,這就是我一直在尋找的。 –

3

這會顯示默認需要味精

<form action="includes/loginprocess.php" method="POST"> 
    <input type="text" name="user" placeholder="Username" required> 
    <input type="password"name="pass" placeholder="Password" required> 
    <input type="submit" value="Login"> 
    </form> 
0

來想一想,你是想告訴用戶哪些空白它們丟失。它真的很需要嗎?如何檢測缺失的空白並返回「字段xxx缺失」消息?例如,你有兩個空格,用戶名和密碼,如果用戶沒有填寫他們,你可以指出「用戶名是必需的」。