我从网络表单获取用户输入,如下所示:
Dim t_ResolvedID As TextBox = DirectCast(gvrow.FindControl("editResolved"), TextBox)
Dim t_CommentsID As TextBox = DirectCast(gvrow.FindControl("editComments"), TextBox)
我想限制可接受的输入如下:
截至目前,我正在执行此错误处理,如下所示:
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
答案 0 :(得分: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