How to block entry of non-numeric string into a textbox-VBForums
Results 1 to 16 of 16

Thread: How to block entry of non-numeric string into a textbox

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    239

    How to block entry of non-numeric string into a textbox

    This is how I convert an ordinary VB6 textbox to an integer textbox:
    Code:
    Public Sub KeyPressAllowNonNegIntOnly(ByRef KeyAscii As Integer)
       Dim ValidKeyAscii             As Boolean
       
       'Blocking unacceptable characters
       If (KeyAscii >= Asc("0")) And (KeyAscii <= Asc("9")) Then
          ValidKeyAscii = True
       ElseIf (KeyAscii < 32) Then
          ValidKeyAscii = True
       Else
          ValidKeyAscii = False
       End If
       
       'Finalizing
       If Not ValidKeyAscii Then
          KeyAscii = 0
       End If
    End Sub
    And an example of how I call it:
    Code:
    Private Sub txtCustomerRefNum_KeyPress(KeyAscii As Integer)
       Call KeyPressAllowNonNegIntOnly(KeyAscii)
    End Sub
    This way the application allows the entry of only numbers (0..9) and nothing else.

    I always thought this technique was perfect!!!
    Now I happened to see that I was so badly wrong!!!
    In fact the above technique lets the user type in only numbers, and it does so perfectly.
    But it does NOTHING to prevent the user from pasting a non numeric string in the textbox
    The user cannot type abc, but can open a Notepad and type abc in there, copy it, and paste it into this textbox.
    My current code (the above code) does not block this.

    How can I block pasting non-numeric strings?
    Please note that pasting valid (numeric) strings should be allowed.
    Please advise.
    Thanks.

  2. #2
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    11,629

    Re: How to block entry of non-numeric string into a textbox

    You could check in the change event possibly using the IsNumeric() function would be one option.
    You could wait and check in the validation event
    You could use a masked edit control

  3. #3
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    15,558

    Re: How to block entry of non-numeric string into a textbox

    Just a tip about IsNumeric(). Function can return true for strings like "&hFE", "&o34", and "2E+0". If that is ok but only 'integer' should be displayed, convert the pasted string to digits before displaying
    Insomnia is just a byproduct of, "It can't be done"

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {GDI+ Classes/Samples} {Unicode Open/Save Dialog} {Icon Organizer/Extractor}
    {VB and DPI Tutorial} {XP/Vista Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    239

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by LaVolpe View Post
    Just a tip about IsNumeric(). Function can return true for strings like "&hFE", "&o34", and "2E+0". If that is ok but only 'integer' should be displayed, convert the pasted string to digits before displaying
    Thanks.
    How can I convert strings like "&hFE", "&o34", and "2E+0" to digits?

  5. #5
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    5,781

    Re: How to block entry of non-numeric string into a textbox

    I'll take a stab at that....only through Googling (and my limited knowledge of the Format() function), I came up with this:

    Code:
    Private Sub Command1_Click()
        Dim x As Double
        x = Format(Combo1.Text, "0.000000000000")
        Text1.Text = CStr(x)
    End Sub
    
    
    
    Private Sub Form_Load()
        Combo1.AddItem ("12345E-3")
        Combo1.AddItem ("&hFE")
        Combo1.AddItem ("&o34")
        Combo1.AddItem ("2E+0")
        Combo1.ListIndex = 0
        
    End Sub
    Not sure if that is correct or not....I am sure someone will verify or tell me it's completely wrong....uses just a Command button, a combobox and a textbox

  6. #6
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    15,558

    Re: How to block entry of non-numeric string into a textbox

    I might prefer this format since whole numbers are only wanted:
    Code:
    If IsNumeric(pastedText) Then MsgBox CStr(Format(pastedText,"#"))
    Can this cause a potential problem on non-US regional settings?
    Insomnia is just a byproduct of, "It can't be done"

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {GDI+ Classes/Samples} {Unicode Open/Save Dialog} {Icon Organizer/Extractor}
    {VB and DPI Tutorial} {XP/Vista Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  7. #7
    Addicted Member
    Join Date
    Feb 2017
    Posts
    190

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by LaVolpe View Post
    I might prefer this format since whole numbers are only wanted:
    Code:
    If IsNumeric(pastedText) Then MsgBox CStr(Format(pastedText,"#"))
    Can this cause a potential problem on non-US regional settings?
    If don't know if problems, but it will behave different in the case there are dots and commans in the string, according to the decimal separator and the thousands separator of the regional settings.

  8. #8
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    15,558

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by Eduardo- View Post
    If don't know if problems, but it will behave different in the case there are dots and commans in the string, according to the decimal separator and the thousands separator of the regional settings.
    Well, can't really use CStr(CLng(someText)) because that could be too limited, as the pasted text may exceed min/max long values. If only whole numbers are needed, the most obvious solution may be best: make that a requirement to the user & walk through the characters, rejecting any pasted text that contains other than 0-9 characters?
    Insomnia is just a byproduct of, "It can't be done"

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {GDI+ Classes/Samples} {Unicode Open/Save Dialog} {Icon Organizer/Extractor}
    {VB and DPI Tutorial} {XP/Vista Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  9. #9
    Addicted Member
    Join Date
    Feb 2017
    Posts
    190

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by LaVolpe View Post
    Well, can't really use CStr(CLng(someText)) because that could be too limited, as the pasted text may exceed min/max long values. If only whole numbers are needed, the most obvious solution may be best: make that a requirement to the user & walk through the characters, rejecting any pasted text that contains other than 0-9 characters?
    Yes, I agree.

    Something like this:

    Code:
    Private Sub Text1_Change()
        Dim ss As Long
        
        If Not AreAllDigits(Text1.Text) Then
            ss = Text1.SelStart
            Text1.Text = OnlyDigits(Text1.Text)
            Text1.SelStart = ss
        End If
    End Sub
    
    Private Function OnlyDigits(nText As String) As String
        Dim c As Long
        Dim Chr As String
        
        For c = 1 To Len(nText)
            Chr = Mid(nText, c, 1)
            If IsNumeric(Chr) Then
                OnlyDigits = OnlyDigits & Chr
            End If
        Next c
    End Function
        
    Private Function AreAllDigits(nText As String) As Boolean
        Dim c As Long
        Dim Chr As String
        
        For c = 1 To Len(nText)
            Chr = Mid(nText, c, 1)
            If Not IsNumeric(Chr) Then
                Exit Function
            End If
        Next c
        AreAllDigits = True
    End Function
    Last edited by Eduardo-; Apr 17th, 2017 at 04:48 PM.

  10. #10
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    5,781

    Re: How to block entry of non-numeric string into a textbox

    After rereading the OP...I agree. If someone pastes in non digit numbers, then kick it back, alerting the paster (I guess that is not a word). OP veered from his original post when responding to LaVolpe, but I think what he really wants is just 0-9 in that textbox...that's easy enough...check on lostfocus (if pasted in), or on a command_click to 'do something with' the info in the textbox.

  11. #11
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    30,461

    Re: How to block entry of non-numeric string into a textbox

    What about a NumericUpDown? If digits 0-9 are desired, why not just use a NUD and let it take care of validating pasted values?

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  12. #12
    PowerPoster
    Join Date
    Feb 2006
    Posts
    16,315

    Re: How to block entry of non-numeric string into a textbox

    How about something like:

    Code:
    Private Sub TextBoxNumericRestrict( _
        ByVal TextBox As VB.TextBox, _
        Optional ByVal AllowDecimalPt As Boolean, _
        Optional ByVal AllowMinus As Boolean, _
        Optional ByVal AllowPlus As Boolean)
        'Validate TextBox on entry.  Note that for a paste operation the
        'caret is left at the point of the last bad character filtered out.
        Static DecimalPt As String
        Dim Text As String
        Dim CharPos As Long
        Dim Error As Boolean
        Dim SelStart As Long
        Dim GotDecimalPt As Boolean 'Track this, we only allow 1 if allowed.
    
        If AllowDecimalPt And Len(DecimalPt) = 0 Then DecimalPt = Mid$(CStr(1.1), 2, 1)
        With TextBox
            Text = .Text
            If Len(Text) = 0 Then Exit Sub
            CharPos = 1
            SelStart = .SelStart
            Select Case Left$(Text, CharPos)
                Case "+"
                    If Not AllowPlus Then
                        Text = Mid$(Text, 2)
                        Error = True
                        SelStart = 0
                    End If
                    CharPos = 2
                Case "-"
                    If Not AllowMinus Then
                        Text = Mid$(Text, 2)
                        Error = True
                        SelStart = 0
                    End If
                    CharPos = 2
            End Select
            Do While CharPos <= Len(Text)
                Select Case Mid$(Text, CharPos, 1)
                    Case DecimalPt
                        If GotDecimalPt Or Not AllowDecimalPt Then
                            Text = Left$(Text, CharPos - 1) & Mid$(Text, CharPos + 1)
                            SelStart = CharPos - 1
                            Error = True
                        Else
                            GotDecimalPt = True
                            CharPos = CharPos + 1
                        End If
                    Case Is < "0", Is > "9"
                        Text = Left$(Text, CharPos - 1) & Mid$(Text, CharPos + 1)
                        SelStart = CharPos - 1
                        Error = True
                    Case Else
                        CharPos = CharPos + 1
                End Select
            Loop
            If Error Then
                .Text = Text
                .SelStart = SelStart
                Beep
            End If
        End With
    End Sub
    That accepts digits and optionally sign and local decimal point characters.

    Calls:

    Code:
    Private Sub Text1_Change()
        TextBoxNumericRestrict Text1, _
                               chkAllowDecimalPt.Value = vbChecked, _
                               chkAllowMinus.Value = vbChecked, _
                               chkAllowPlus.Value = vbChecked
    End Sub
    
    Private Sub Text2_Change(Index As Integer)
        TextBoxNumericRestrict Text2(Index), _
                               chkAllowDecimalPt.Value = vbChecked, _
                               chkAllowMinus.Value = vbChecked, _
                               chkAllowPlus.Value = vbChecked
    End Sub
    Obviously in a real program you wouldn't have the CheckBox controls though.
    Attached Files Attached Files

  13. #13
    Frenzied Member gibra's Avatar
    Join Date
    Oct 2009
    Location
    ITALY
    Posts
    1,252

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by IliaPreston View Post
    But it does NOTHING to prevent the user from pasting a non numeric string in the textbox
    This code force to accept only number:

    Code:
    Private Const ES_NUMBER = &H2000&
    Private Const GWL_STYLE = (-16)
    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Declare Function GetWindowLong Lib "user32.dll" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
    
    Public Function TextBoxNumeric(ByVal hWnd As Long) As Long
        Dim lngStyle As Long
        Dim lngReturn As Long
        lngStyle = GetWindowLong(hWnd, GWL_STYLE)
        If lngStyle <> 0 Then
            lngReturn = SetWindowLong(hWnd, GWL_STYLE, lngStyle Or ES_NUMBER)
        End If
        TextBoxNumeric = lngReturn
    End Function
    
    
    Private Sub Command1_Click()
        TextBoxNumeric Text1.hwnd
    End Sub

  14. #14
    Frenzied Member
    Join Date
    Jun 2015
    Posts
    1,091

    Re: How to block entry of non-numeric string into a textbox

    Quote Originally Posted by gibra View Post
    This code force to accept only number:

    Code:
    Private Const ES_NUMBER = &H2000&
    per https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx

    Quote Originally Posted by MSDN
    ES_NUMBER Allows only digits to be entered into the edit control. Note that, even with this set, it is still possible to paste non-digits into the edit control.

  15. #15
    Frenzied Member gibra's Avatar
    Join Date
    Oct 2009
    Location
    ITALY
    Posts
    1,252

    Re: How to block entry of non-numeric string into a textbox

    Sorry, I missed something:

    Code:
    Private Sub Text1_Validate(Cancel As Boolean)
        If Not IsNumeric(Text1.Text) Then
            Text1.Text = vbNullString
        End If
    End Sub

  16. #16
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    5,781

    Re: How to block entry of non-numeric string into a textbox

    gibra....LaVolpe says:

    IsNumeric(). Function can return true for strings like "&hFE", "&o34", and "2E+0".
    Hence, if in 'validate', if what he says is true....and I suspect it is...., then that would not work for OP. however, if in the validate, instead just check for ASCII 0-9....yes?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.