Another way on how to restrict the textbox to accept only alpha or numeric characters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lotus18
    Contributor
    • Nov 2007
    • 865

    Another way on how to restrict the textbox to accept only alpha or numeric characters

    Hello World!

    I have a sample code here written in vb .net that restricts the textbox to accept only alpha, alphanumeric or numeric characters.

    [CODE=net]
    Public Enum MyOption
    Alpha = 1
    AlphaNumeric = 2
    Numeric = 3
    End Enum

    Public Sub SetCharacter(By Val CharacterOption As MyOption, _
    ByVal kp As KeyPressEventAr gs)
    Select Case CharacterOption
    Case MyOptions.Alpha
    If Not ( _
    kp.KeyChar Like "[A-Z]" Or _
    kp.KeyChar Like "[a-z]" Or _
    kp.KeyChar = vbBack Or _
    Asc(kp.KeyChar) = 32) Then
    kp.KeyChar = vbNullChar
    End If
    Case MyOptions.Alpha Numeric
    If Not ( _
    kp.KeyChar Like "[A-Z]" Or _
    kp.KeyChar Like "[a-z]" Or _
    kp.KeyChar Like "[ñÑ]" Or _
    kp.KeyChar Like "[0-9]" Or _
    kp.KeyChar = vbBack Or _
    Asc(kp.KeyChar) = 32) Then
    kp.KeyChar = vbNullChar
    End If
    Case MyOptions.Numer ic
    If Not ( _
    kp.KeyChar Like "[0-9]" Or _
    kp.KeyChar = vbBack Or _
    Asc(kp.KeyChar) = 32) Then
    kp.KeyChar = vbNullChar
    End If
    End Select

    End Sub[/CODE]

    Just place the SetCharacter method to the KeyPress event of a textbox, combobox, etc.

    Sample 1. A textbox that accepts only numeric characters
    [CODE=vb6]Private Sub Text1_KeyPress( ByVal sender As Object, ByVal e As System.Windows. Forms.KeyPressE ventArgs) Handles Text1.KeyPress
    SetCharacter(My Option.Numeric, e)
    End Sub[/CODE]

    As you noticed, the SetCharacter method has 2 parameters-CharacterOption and kp.

    CharacterOption - Sets the MyOption value whether you want alpha, alphanumeric, or numeric
    kp - Gets the current key that you have pressed.



    Rey Sean
    Mabuhay ang pinoy : )
  • Montravont
    New Member
    • Sep 2008
    • 10

    #2
    My first thought was... Why? Then I read the end of it and it changed to Oh!.

    Nice, work. Personally I don't tend to need to limit things to alpha or alphanumeric, only numeric. In those cases, if that's the only thing I need to limit on keypress, I'll just write the numeric limiting code once and refer all the keypresses to that one bit of code.

    This is pretty friggin nifty though.

    Comment

    • madankarmukta
      Contributor
      • Apr 2008
      • 308

      #3
      HI,

      Make use of Regular Expressiona.

      Thanks!

      Comment

      • balabaster
        Recognized Expert Contributor
        • Mar 2007
        • 798

        #4
        Your code is a great idea and very useful...howeve r, I thought it might be a bit more extensible in this format, it's also easier to write unit tests for:
        Code:
        Public Enum Options
          Alpha
          AlphaNumeric
          Numeric
        End Enum
         
        Function Pattern(ByVal CharOpt As Options)
         
          Dim s = String.Empty
          Select Case CharOpt
              Case Options.Alpha
                  s = "A-Za-z"
              Case Options.AlphaNumeric
                  s = "\w"
              Case Options.Numeric
                  s = "\d"
          End Select
         
          'All my patterns allow spaces... 
          Return String.Format("[{0}\s]", s)
         
        End Function
         
        Public Sub AllowChars(ByVal CharOpt As Options, _
                              ByVal kp As KeyPressEventArgs)
         
          'Create list of always allowable keys
          Dim Allow As Keys() = {Keys.Delete, Keys.Back}
         
          'If not one of the allowable keys we predefined, 
          'then check the characters entered against the 
          'pattern defined for the selected pattern option, 
          'if it doesn't match, then ditch it...
          If Not Allow.Contains(AscW(kp.KeyChar)) Then
            If Not Regex.IsMatch(kp.KeyChar, Pattern(CharOpt)) Then
              kp.KeyChar = ControlChars.NullChar
            End If
          End If
         
        End Sub
         
        Private Sub KeyPressed(ByVal sender As Object, _
                               ByVal e As KeyPressEventArgs) _
          Handles tb1.KeyPress
         
          AllowChars(Options.Numeric, e)
         
        End Sub

        Comment

        • lotus18
          Contributor
          • Nov 2007
          • 865

          #5
          I will take your comments as complements. Anyway, thank you guys for your comments : )

          To madankarmukta, I was thinking about RegularExpressi ons and I know this is more appropriate and more acceptable than mine LOL. I found a lot of tutorials in the net using this and as you can see in the title "Another way on how ...", so I created another way on how to handle this.



          Rey Sean

          Comment

          • SioSio
            Contributor
            • Dec 2019
            • 272

            #6
            Just write a few lines to the TextChanged event that fires when the text changes.
            The following is an example of alphanumeric characters.
            Code:
            Private Sub TextBox1_TextChange(sender As System.Object, e As System.EventArgs)
            	Dim r As New System.Text.RegularExpressions.Regex("[^A-Za-z0-9]")
                    Dim i As Integer
                    i = textbox1.SelectionStart
                	TextBox1.Text = r.Replace(TextBox1.Text, "")
                	TextBox1.SelectionStart = i
            End Sub

            Comment

            Working...