2012-11-19 51 views
0

我從web形式獲取用戶輸入如下:構建此錯誤處理的最有效方式是什麼?

Dim t_ResolvedID As TextBox = DirectCast(gvrow.FindControl("editResolved"), TextBox) 
Dim t_CommentsID As TextBox = DirectCast(gvrow.FindControl("editComments"), TextBox) 

我想限制可接受的輸入如下:

  • t_ResolvedID只應是一個正整數(無alpha字符)
  • t_CommentsID不應超過4000個字符。此外,如果t_CommentsID.Text包含一個單引號,用兩個單引號

截至目前取代它,我如下執行該錯誤處理:

If IsNumeric(t_ResolvedID.Text) Then 
    resolved = Integer.Parse(t_ResolvedID.Text) 
Else 
    ShowMessage("Error! Invalid character in 'Resolved' field.") 
    errorCount += 1 
End If 

If Integer.Parse(t_ResolvedID.Text) < 0 Then 
    ShowMessage("Error! 'Resolved' field cannot be negative!") 
    errorCount += 1 
End If 

If t_CommentsID.Text.Length > 4000 Then 
    errorCount += 1 
    ShowMessage("Error! The 'Comments' field cannot exceed 4000 characters!") 
End If 

'Transform single quote into two single quotes to avoid SQL errors 
If t_CommentsID.Text.Contains("'") Then 
    comments = t_CommentsID.Text.Replace("'", "''") 
End If 

If t_CommentsID.Text.Length < 4000 And Not t_CommentsID.Text.Contains("'") Then 
    comments = t_CommentsID.Text 
End If 

我覺得有一個更好的儘管如此。現在,我只保留一個錯誤計數,因爲我不想執行帶有錯誤數據的最終更新SQL查詢。所以我在運行查詢之前檢查errorCount是否等於0。我怎樣才能讓這更高效?

我使用AJAX的ShowMessage()函數,所以我想保持能夠通知用戶錯誤,如果可能的話。

謝謝!

編輯:我結束了修改我的代碼如下:

If Not IsNumeric(t_ResolvedID.Text) Then 
    errors += "Error! Invalid character in 'Resolved' field<br/>" 
Else 
    resolved = Integer.Parse(t_ResolvedID.Text) 
    If resolved < 0 Then 
     errors += "Error! 'Resolved' field cannot be negative!<br/>" 
    Else 
     resolved = t_ResolvedID.Text 
    End If 
End If 

If t_CommentsID.Text.Length > 4000 Then 
    'errorCount += 1 
    errors += "Error! 'Comments' field cannot exceed 4000 characters!<br/>" 
End If 

'Transform single quote into two single quotes to avoid SQL errors 
If t_CommentsID.Text.Contains("'") Then 
    comments = t_CommentsID.Text.Replace("'", "''") 
End If 

If t_CommentsID.Text.Length < 4000 And Not t_CommentsID.Text.Contains("'") Then 
    comments = t_CommentsID.Text 

End If 
+1

我沒有發現你的代碼有太多錯誤。您應該重用「已解決」,而不是在第二次測試中再次解析字符串。你可能想要連接你的所有消息,並在最後一起顯示它們。您可能還想看看一些驗證控件以獲得更專業的外觀,但您可能會花費幾天的時間,不確定您的目標受衆是什麼。 – PatFromCanada

+0

非常好。謝謝。顯然,解析字符串會導致更好的性能,我會做出改變。此外,連接字符串,然後在最後顯示它們是一個好主意。雖然驗證控件意味着什麼?我的目標受衆主要由會計師組成,網站基本上從數據庫中獲取數字,進行一些數學計算,然後在GridView中將其輸出給用戶。 – TimeBomb006

+2

看看[MSDN驗證控件](http://msdn.microsoft.com/en-us/library/debza5t0(v = vs.100).aspx) – PatFromCanada

回答

1

你的意思是這樣的嗎?

If Not IsNumeric(intString) Then 
    errors += "Error! Invalid character in 'Resolved' field<br/>" 
Else 
    If Not Integer.TryParse(intString, resolved) Then 
     errors += "Error! Resolved must be an integer." 
    End If 
end if 
相關問題