Results 1 to 3 of 3

Thread: how to validate textbox allows only numeric and decimal in vb.net

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2008
    Posts
    103

    how to validate textbox allows only numeric and decimal in vb.net

    i need to validate a textbox

    it should take either decimal values or integers and max length is 16

    if it takes decimal value as input then it should contain only 14 digits in decimal place and 2 digits in fraction part
    eg(1234567.12-valid) but (12345678.123 - invalid) and also(123456.12345- invalid)

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: how to validate textbox allows only numeric and decimal in vb.net

    What you're asking for is not as simple as you think. Here's some code that will get you most of the way there, but it still won't stop the user pasting invalid data in:
    vb.net Code:
    1. Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    2.     Dim keyChar = e.KeyChar
    3.  
    4.     If Char.IsControl(keyChar) Then
    5.         'Allow all control characters.
    6.     ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
    7.         Dim text = Me.TextBox1.Text
    8.         Dim selectionStart = Me.TextBox1.SelectionStart
    9.         Dim selectionLength = Me.TextBox1.SelectionLength
    10.  
    11.         text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)
    12.  
    13.         If Integer.TryParse(text, New Integer) AndAlso text.Length > 16 Then
    14.             'Reject an integer that is longer than 16 digits.
    15.             e.Handled = True
    16.         ElseIf Double.TryParse(text, New Double) AndAlso text.IndexOf("."c) < text.Length - 3 Then
    17.             'Reject a real number with two many decimal places.
    18.             e.Handled = True
    19.         End If
    20.     Else
    21.         'Reject all other characters.
    22.         e.Handled = True
    23.     End If
    24. End Sub

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Nov 2008
    Posts
    103

    Re: how to validate textbox allows only numeric and decimal in vb.net

    thank you so much its working

Posting Permissions

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



Click Here to Expand Forum to Full Width