2012-11-19 50 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 
相关问题