0

我从 Web 表单中获取用户输入,如下所示:

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

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

  • t_ResolvedID 只能是正整数(无字母字符)
  • 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
4

1 回答 1

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
于 2012-11-19T16:18:45.080 回答