简体   繁体   中英

VB.NET conditionals with a regex match

I constructed a code that checks if the content in a textbox is a string or an integer. What i do is the following :

Imports System.Text.RegularExpressions

Public Class Form1

Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click

    Dim value As String = txtBox.Text

    Dim i As Integer
    If (Integer.TryParse(value, i)) = True Then
        If IsValid(value) = True Then
            MsgBox(value & " is a correct entry")
        Else
            MsgBox("Not a correct TVA number !")
        End If
    Else
        MsgBox(value & " is a string")
    End If
End Sub

Function IsValid(ByRef value As String) As Boolean
    Return Regex.IsMatch(value, "^0[1-9]{9}$")
End Function

End Class

Now all is working just fine, untill i type in 11 or more numbers in the textbox, after which the code suddenly tells me that (eg) 012345678912 is a string (!)

So to be clear, when i type the following numbers :

  • 12345 -> msgbox tells me the entry is "Not a correct TVA number"
  • 123456789 -> msgbox tells me the entry is "Not a correct TVA number"
  • 0123456789 -> msgbox says it's OK
  • 01234567891 -> msgbox tells me the entry is "Not a correct TVA number"
  • 012345678912 -> msgbox tells me the entry is suddenly a string !
  • some text -> msgbox says it's a string so it's OK

Maybe i'm missing something obvious here, but i looked at the code over and over again and i tested the regular expressions a few times in other applications, where they work just fine.

What is it that i'm overlooking here please ?

Regards Wim

That value is too large for an Integer , so it overflows and Int32.TryParse returns false .

You could use this:

If value.All(AddressOf Char.IsDigit) Then
    If IsValid(value) = True Then
        MsgBox(value & " is a correct entry")
    Else
        MsgBox("Not a correct TVA number !")
    End If
Else
    MsgBox(value & " is a string")
End If

or use Int64.TryParse instead which allows larger numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM