A function to only allow numeric input in a textbox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mshmyob
    Recognized Expert Contributor
    • Jan 2008
    • 903

    A function to only allow numeric input in a textbox

    Here is a way to limit user input in a textbox to only numeric characters.

    I have created a function and I put mine in a Class module that holds my custom functions. The function is called from the KEYPRESS event of any textbox control where you want to limit to numeric input.

    The only parameter you may wish to change is the last parameter which determines the number of digits to the right of the decimal place. This sample code limits the input to 2 decimal places.

    Code for KEYPRESS event

    [code=vb]
    Dim myTextBox As TextBox
    myTextBox = Me.ActiveContro l
    If myMiscClass.myN umOnly(e.KeyCha r, Me.ActiveContro l.Text, myTextBox.Selec tionStart, 2) = True Then
    e.Handled = True
    Else
    e.Handled = False
    End If
    If e.KeyChar = Chr(13) Then GetNextControl( Me.ActiveContro l, True).Focus() 'Enter key moves to next control
    [/code]

    Code for Function (I put this in it's own class module (so I only need it once) but you may put it in your form module if you wish.)

    [code=vb]
    '************** *************** *************** *********
    ' myNumOnly()
    ' Purpose: Limits textbox input to numeric only
    ' Inputs: strKeyPress, key pressed
    ' strText, current text in textbox
    ' intPosition, current cursor position in textbox
    ' intDecimal, number of decimal places required
    ' ' Returns: False/True - discard keystroke/valid key
    '************** *************** *************** *********
    Shared Function myNumOnly(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean

    Dim dot As Integer, ch As String

    If Not Char.IsDigit(st rKeyPress) Then myNumOnly = True
    If strKeyPress = "-" And intPosition = 0 Then myNumOnly = False 'allow negative number
    If strKeyPress = "." And strText.IndexOf (".") = -1 Then myNumOnly = False 'allow single decimal point
    dot = strText.IndexOf (".")
    If dot > -1 Then 'limit to set decimal places
    ch = strText.Substri ng(dot + 1)
    If ch.Length > (intDecimal - 1) Then myNumOnly = True
    End If
    If strKeyPress = Chr(8) Then myNumOnly = False 'allow Backspace
    Return myNumOnly
    End Function
    [/code]

    Feel free to ask any questions.

    cheers,
  • yarbrough40
    Contributor
    • Jun 2009
    • 320

    #2
    Thanks for this! I have written it in a notepad for posterity.

    Comment

    Working...