Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 48,685 times

Related Categories

Accept only numbers in a text field

Often, to ensure that users enter only numbers in a text field,
you'll want to validate the text as they enter it. The textbox's
Change() event provides the best place to do so. However, simply
using the IsNumeric() function alone won't do the trick. For
instance, suppose you created the following procedure

Private Sub Text1_Change()
If Not IsNumeric(Text1.Text) Then
    Text1.Text = ""
End If


Under these circumstances, if the user entered the number -333,
the control wouldn't accept it because the beginning dash isn't
a number. Instead, consider using the following function

Private Sub Text1_Change()
If Not ValidateNumeric(Text1.Text) Then
    Text1.Text = ""
End If
End Sub

Private Function ValidateNumeric(strText As String) _
    As Boolean
ValidateNumeric = CBool(strText = "" _
    Or strText = "-" _
    Or strText = "-." _
    Or strText = "." _
    Or IsNumeric(strText))
End Function

© 2001 Element K Journals, a division of Element K Press LLC ("Element K"). Element K and the Element K logo are trademarks of Element K LLC

Comments

  • Re: [147] Accept only numbers in a text field

    Posted by chandra219 on 17 Feb 2007

    Limit input in textbox that allows only digits, backspaces and one decimal point to be entered .


    Method 1 using keypress event:
    Private sub Text1_KeyPress(KeyAscii As Integer)<...

  • What I use...

    Posted by Xenophanes on 09 Jun 2005

    Public Function CheckNumeric (strTest As String) As String

    Dim I%

    On Error GoTo NotNumeric
    I% = strTest
    CheckNumeric = strTest
    Exit Function

    NotNumeric:
    CheckNumeric= Left$(strTest, Len(s...

  • A more better way?

    Posted by mr_mellow on 10 Dec 2002

    KeyPress event is the better way to test user input. However, it requires a more elaborate code for user input testing.

    This example shows a moving decimal point and toggling for negative sign. No...

  • Another Method

    Posted by the_liberator on 24 Apr 2002

    Keypress can also be used for this.

    [code]
    Private Sub Text1_KeyPress(KeyAscii as Integer)
    'Ignore negatives
    If KeyAscii = 45 then goto EndProc
    'If Key pressed is not numeric then make ke...