TextChanged事件中加长度校验后VerifyContent函数始终返回false问题
问题分析与解决方案
问题根源
10位数字的范围是1000000000到9999999999,而VB.NET中Integer类型的最大值仅为2147483647,当输入的10位数字超过这个上限时,Integer.TryParse会转换失败,直接导致VerifyContent返回false。这就是单独调用函数时输入短位整数正常,但在TextChanged事件限定10位后必然校验失败的核心原因。
修复方案
将校验使用的整数类型替换为Long(支持范围更大,最大值可达9223372036854775807),修改后的代码如下:
Public Function VerifyContent(input As String, VerificationType As Integer) As Boolean VerifyContent = False If VerificationType = 1 Then ' 类型1用于检查值是否为整数 Dim longValue As Long If Long.TryParse(input, longValue) Then ' 改用Long.TryParse适配10位数字 VerifyContent = True End If End If End Function Private Sub Tariff_TextChanged(sender As Object, e As EventArgs) Handles Tariff.TextChanged If Me.Tariff.Text.Length <> 10 Then Console.WriteLine("长度校验未通过。") Exit Sub End If If VerifyContent(Me.Tariff.Text, 1) Then Console.WriteLine("内容校验通过。") MsgBox("运行正常!") Else Console.WriteLine("内容校验未通过。") End If End Sub
额外优化思路
如果这个10位文本仅需确保是纯数字格式、不需要参与数值计算,也可以直接用正则表达式校验,效率更高:
' 直接校验10位纯数字字符串 If System.Text.RegularExpressions.Regex.IsMatch(Me.Tariff.Text, "^\d{10}$") Then Console.WriteLine("内容校验通过。") MsgBox("运行正常!") Else Console.WriteLine("内容校验未通过。") End If
内容的提问来源于stack exchange,提问作者Kristian May
相关产品推荐
相关产品推荐

