Matt
Matt

Reputation: 191

Checking to see if text box input is numeric

I've done some research on this and still cannot get my program to work. I simply need to check the text box to see if the user input is a numeric value, or not (with the exception of a "." and or "/")

My code so far,

 Private Sub Num1_KeyPress(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Num1.KeyPress
    Dim UserEntry As Boolean
    If UserEntry = IsNumeric(False) Then
        MessageBox.Show("That's not numeric!")
    End If
End Sub

Upvotes: 1

Views: 52310

Answers (7)

rbassett
rbassett

Reputation: 391

On a slight tangent, according to the top answer to the question checking for numeric value entered in text box in visual basic, there is also the method .TryParse which is considered a better solution than IsNumeric :

The first reason is that with TryParse you also get the result of the conversion while with IsNumeric you would have to do the conversion after the check.

The second reason is that you could give to IsNumeric whatever object you want (also a Button for example) and it accepts it. You would never discover this kind of errors at compile time. Instead, with TryParse, you could only pass a string as its first parameter.

Upvotes: 0

Fake Faker
Fake Faker

Reputation: 1

' Validates textboxes for numeric only keystrokes.  Hook this up to the 
' PreviewTextInput of the desired textbox
Private Sub SetTextboxNumericOnly(sender As Object,
                                  e As TextCompositionEventArgs)

    Dim regex As New System.Text.RegularExpressions.Regex("[^0-9]+")
    e.Handled = regex.IsMatch(e.Text)

End Sub

Keep in mind that you still need to check if the textbox contains a value in case they delete the contents of the textbox. This routine ensures it is always numeric and so there is no longer a need to check.

Upvotes: 0

Cesar Alpendre
Cesar Alpendre

Reputation: 1

Private Sub tbYear_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbYear.KeyPress
    If e.KeyChar < Chr(48) Or e.KeyChar > Chr(57) Then
        e.KeyChar = Nothing
    End If
End Sub

Upvotes: 0

Trevor Tubbs
Trevor Tubbs

Reputation: 2117

I recommend handling TextChanged and checking the whole number instead of a single character.

Private Sub Num1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles Num1.TextChanged
        If IsInputNumeric(Num1.Text) Then
            'handle numeric input
        Else
            'handle not a number
        End If
    End Sub

    Private Function IsInputNumeric(input As String) As Boolean
        If String.IsNullOrWhiteSpace(input) Then Return False
        If IsNumeric(input) Then Return True
        Dim parts() As String = input.Split("/"c)
        If parts.Length <> 2 Then Return False
        Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
    End Function

Upvotes: 9

DeanOC
DeanOC

Reputation: 7262

I find that this sort of validation is much easier to do either in the textBox's LostFocus eventHandler, or at the Form level, e.g. when the user clicks the OK button.

Then you can do your validation as follows

a) Does the textbox contain any chars outside of "0123456789./" If so then non-numeric

b) Split the text wherever the "/" character appears (if any), and then use the IsNumeric() function on each substring. If any of them are not numeric, then the text is not numeric.

This does assume that you are allowing 1/2/2, .i.e. 1/4. If not then you also have to check that there is a max of 1 "/" chars in your string.

Upvotes: 0

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

I think you better be using TextBox.KeyUp event, it passes the KeyEventArgs. Try this :

Private Sub Num1_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles Num1.KeyUp

    Dim isDigit As Boolean = Char.IsDigit(ChrW(e.KeyValue))
    Dim isKeypadNum As Boolean = e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9
    Dim isBackOrSlashOrPeriod As Boolean = (e.KeyCode = Keys.Decimal Or e.KeyCode = Keys.Oem2 Or e.KeyCode = Keys.Back Or e.KeyCode = Keys.OemPeriod)

    If Not (isDigit Or isKeypadNum Or isBackOrSlashOrPeriod) Then
        MessageBox.Show("That's not numeric!")
    End If

End Sub

Upvotes: 3

Esselans
Esselans

Reputation: 1546

Public Function onlyNumbers(ByVal KeyChar As Char) As Boolean
    Dim allowedChars As String

    allowedChars = "0123456789./" 

    If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then 
        Return True
    End If

    Return False
End Function

true means an invalid char.

On keypress you need to do:

e.handled = onlyNumbers(e.keychar)

Upvotes: 0

Related Questions