none
validating a textbox to allow numbers only and displaying an error message RRS feed

  • Question

  • hie guys 

    i really need help with this. How do i validate a text box to only accept numbers and display an error message if a letter or invalid characters are entered . I am using Visual studio 2012 

    Wednesday, June 12, 2019 1:03 PM

All replies

  • Hi

    I got 46385 results when I typed "textbox numbers only" into the Search box at the top of the Forum page(s)

    Maybe one of them answers your question.


    Regards Les, Livingston, Scotland



    • Edited by leshay Wednesday, June 12, 2019 1:10 PM
    Wednesday, June 12, 2019 1:08 PM
  • Hi

    Here is the code for one (of many many possibilities) that I wrote as the answer to a previous post. This one restricts User input to "0123456789.+-" & BackSpace, showing a warning background colour if User enters outside permitted (or tries to enter more than one Decimal point). As you are asking for an error message, maybe you could adapt this code to show a MessageBox instead of changing BC?

    This is a stand alone example project, and only needs a default Form1 with a Default TextBox1.

    ' Limit user input
    ' Numeric TextBox Input
    ' Form1 with TextBox1
    Option Strict On
    Option Explicit On
    Public Class Form1
    	Dim TBdefaultBC, ErrorBC As New Color
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' get TB BC as User may have
    		' set own choice.
    		TBdefaultBC = TextBox1.BackColor
    		' set ERROR BC to be used
    		ErrorBC = Color.Pink
    	End Sub
    	Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    
    		TextBox1.BackColor = TBdefaultBC
    
    		Dim t As TextBox = DirectCast(sender, TextBox)
    
    		t.Text = t.Text.Replace("."c, ","c)
    
    		If t.Text.StartsWith(".") Or t.Text.StartsWith(",") Then t.Text = "0" & t.Text
    
    		t.SelectionStart = t.MaxLength
    		t.SelectionLength = 0
    
    		Dim tb() As Char = t.Text.ToCharArray
    
    		Dim allowed As String = "0123456789.+-" & Chr(8)
    
    		If allowed.IndexOf(e.KeyChar) = -1 Or (e.KeyChar = "." And tb.Count(Function(c) c = "." AndAlso tb.Count > 0) > 0) Or (e.KeyChar = "," And tb.Count(Function(c) c = "," AndAlso tb.Count > 0) > 0) Or (e.KeyChar = "-" And tb.Count > 0) Or (e.KeyChar = "+" And tb.Count > 0) Or (e.KeyChar = "." And t.Text.Contains(",")) Then
    			e.Handled = True
    			TextBox1.BackColor = ErrorBC
    		End If
    	End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, June 12, 2019 1:27 PM
    Wednesday, June 12, 2019 1:26 PM
  • Hello,

    You could have a custom TextBox as per below which prevents alpha characters entered or paste from the Windows Clipboard.

    Public Class NumericTextbox
        Inherits TextBox
    
        Const WM_PASTE As Integer = &H302
        Public ErrorProvider As New ErrorProvider
        Public Enum DecimalDigits
            ZeroDigits
            OneDigit
            TwoDigits
            ThreeDigits
        End Enum
        Public Property DecimalPlaces As DecimalDigits
        <ComponentModel.Category("Behavior")>
        <ComponentModel.Description("Error message for when user enters invalid data.")>
        Public Property ErrorText() As String
        <ComponentModel.Browsable(False)>
        Public ReadOnly Property DoubleValue As Double
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CDbl(Text)
                End If
            End Get
        End Property
        <ComponentModel.Browsable(False)>
        Public ReadOnly Property DecimalValue As Decimal
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CDec(Text)
                End If
            End Get
        End Property
        <ComponentModel.Browsable(False)>
        Public ReadOnly Property IntegerValue As Integer
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CInt(Text)
                End If
            End Get
        End Property
        <ComponentModel.Browsable(False)>
        <ComponentModel.Description("Used for formatting value.")>
        Public ReadOnly Property FormattedValue As String
            Get
                Select Case DecimalPlaces.ToString
                    Case "ZeroDigits"
                        Return DoubleValue.ToString("F0")
                    Case "OneDigit"
                        Return DoubleValue.ToString("F1")
                    Case "TwoDigits"
                        Return DoubleValue.ToString("F2")
                    Case "ThreeDigits"
                        Return DoubleValue.ToString("F3")
                    Case Else
                        Return ""
                End Select
            End Get
        End Property
        Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
            Dim value As String = Text
    
            value = value.Remove(SelectionStart, Me.SelectionLength)
            value = value.Insert(SelectionStart, e.KeyChar)
    
            e.Handled = value.LastIndexOf("-", StringComparison.Ordinal) > 0 Or
                        Not (Char.IsControl(e.KeyChar) OrElse Char.IsDigit(e.KeyChar) OrElse
                             (e.KeyChar = "."c And
                              Not Text.Contains(".") Or e.KeyChar = "."c And
                                                        SelectedText.Contains(".")) OrElse (e.KeyChar = "-"c And
                                                                                            Me.SelectionStart = 0))
            If e.Handled Then
                ErrorProvider.SetError(Me, ErrorText)
            Else
                ErrorProvider.SetError(Me, "")
            End If
            MyBase.OnKeyPress(e)
    
        End Sub
        Protected Overrides Sub WndProc(ByRef m As Message)
            If m.Msg = WM_PASTE Then
                Dim value As String = Text
                value = value.Remove(SelectionStart, SelectionLength)
                value = value.Insert(SelectionStart, Clipboard.GetText)
                Dim result As Decimal = 0
                If Not Decimal.TryParse(value, result) Then
                    Return
                End If
            End If
            MyBase.WndProc(m)
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, June 12, 2019 2:00 PM
    Moderator
  • Hi,

    code:

    Public Class Form1
        Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar < "0"c OrElse e.KeyChar > "9"c Then
                e.Handled = True
                MsgBox("ERROR")
            End If
        End Sub
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 13, 2019 4:32 AM