Blog : Validating a Numeric String in VB.NET
Validating a Numeric String in VB.NET
While working on a program recently, I needed to guarantee that some text input contained only numbers. (The app required the user to enter a numeric serial number.) I bingled the web for a while to see if anyone had any better ideas about how to do it than I did and I discovered (Yet again!!) that there is a lot of trash advice out there. This article covers the common recommendations and then the one I recommend. (Which actually isn't very common.)
First, some code to test the validation. I created a quick form with a TextBox, a Button, and two labels occupying the same location to report the answer by making one or the other visible. All the tests were similar to this:
Private Sub btnValidateString_Click(
ByVal sender As System.Object,
ByVal e As System.EventArgs
) Handles btnValidateString.Click
If -- Test for numeric characters --
lblNotInt.Visible = True
Exit Sub
End If
lblInt.Visible = True
End Sub
Private Sub TestStringIn_TextChanged(
ByVal sender As System.Object,
ByVal e As System.EventArgs
) Handles TestStringIn.TextChanged
lblInt.Visible = False
lblNotInt.Visible = False
End Sub
One of the most common techniques recommended is to use the VB.NET IsNumeric method.
If Not IsNumeric(TestStringIn.Text) Then
lblNotInt.Visible = True
Exit Sub
End If
That works to screen out alpha characters, but it misses commas periods and spaces (before and after). So you have to add tests for them as well, something like this:
If InStr(1, TestStringIn.Text, ".") <> 0 Then
lblNotInt.Visible = True
Exit Sub
End If
Each one will need it's own test.
You can get better results by testing the opposite. You see this one a lot too:
Dim iLen As Integer = Len(TestStringIn.Text)
If iLen > 0 Then
For i As Integer = 1 To iLen
If Not Mid(TestStringIn.Text, i, 1) _
Like "[0-9]" Then
lblNotInt.Visible = True
Exit Sub
End If
Next
End If
This works better and it's shorter. But if you're going to do it this way, why not use the technology invented to do it: Regular Expressions. (I have a more complete tutorial on RegEx here: Regular Expressions in VB.NET)
Dim intRegexPattern As New _
System.Text.RegularExpressions.Regex("^[0-9]*$")
If Not intRegexPattern.IsMatch(TestStringIn.Text) Then
lblNotInt.Visible = True
Exit Sub
End If