472,967 Members | 1,978 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,967 developers and data experts.

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

866 512MB
Hello World!

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

Expand|Select|Wrap|Line Numbers
  2. Public Enum MyOption
  3.         Alpha = 1
  4.         AlphaNumeric = 2
  5.         Numeric = 3
  6.     End Enum
  8.  Public Sub SetCharacter(ByVal CharacterOption As MyOption, _
  9. ByVal kp As KeyPressEventArgs)
  10.         Select Case CharacterOption
  11.             Case MyOptions.Alpha
  12.                 If Not ( _
  13.                     kp.KeyChar Like "[A-Z]" Or _
  14.                     kp.KeyChar Like "[a-z]" Or _
  15.                     kp.KeyChar = vbBack Or _
  16.                     Asc(kp.KeyChar) = 32) Then
  17.                     kp.KeyChar = vbNullChar
  18.                 End If
  19.             Case MyOptions.AlphaNumeric
  20.                 If Not ( _
  21.                         kp.KeyChar Like "[A-Z]" Or _
  22.                         kp.KeyChar Like "[a-z]" Or _
  23.                         kp.KeyChar Like "[ρΡ]" Or _
  24.                         kp.KeyChar Like "[0-9]" Or _
  25.                         kp.KeyChar = vbBack Or _
  26.                         Asc(kp.KeyChar) = 32) Then
  27.                     kp.KeyChar = vbNullChar
  28.                 End If
  29.             Case MyOptions.Numeric
  30.                 If Not ( _
  31.                      kp.KeyChar Like "[0-9]" Or _
  32.                      kp.KeyChar = vbBack Or _
  33.                      Asc(kp.KeyChar) = 32) Then
  34.                     kp.KeyChar = vbNullChar
  35.                 End If
  36.         End Select
  38.     End Sub
Just place the SetCharacter method to the KeyPress event of a textbox, combobox, etc.

Sample 1. A textbox that accepts only numeric characters
Expand|Select|Wrap|Line Numbers
  1. Private Sub Text1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Text1.KeyPress
  2.         SetCharacter(MyOption.Numeric, e)
  3.     End Sub
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 : )
Dec 6 '08 #1
5 28395
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.
Dec 8 '08 #2
308 256MB

Make use of Regular Expressiona.

Dec 9 '08 #3
797 Expert 512MB
Your code is a great idea and very useful...however, I thought it might be a bit more extensible in this format, it's also easier to write unit tests for:
Expand|Select|Wrap|Line Numbers
  1. Public Enum Options
  2.   Alpha
  3.   AlphaNumeric
  4.   Numeric
  5. End Enum
  7. Function Pattern(ByVal CharOpt As Options)
  9.   Dim s = String.Empty
  10.   Select Case CharOpt
  11.       Case Options.Alpha
  12.           s = "A-Za-z"
  13.       Case Options.AlphaNumeric
  14.           s = "\w"
  15.       Case Options.Numeric
  16.           s = "\d"
  17.   End Select
  19.   'All my patterns allow spaces... 
  20.   Return String.Format("[{0}\s]", s)
  22. End Function
  24. Public Sub AllowChars(ByVal CharOpt As Options, _
  25.                       ByVal kp As KeyPressEventArgs)
  27.   'Create list of always allowable keys
  28.   Dim Allow As Keys() = {Keys.Delete, Keys.Back}
  30.   'If not one of the allowable keys we predefined, 
  31.   'then check the characters entered against the 
  32.   'pattern defined for the selected pattern option, 
  33.   'if it doesn't match, then ditch it...
  34.   If Not Allow.Contains(AscW(kp.KeyChar)) Then
  35.     If Not Regex.IsMatch(kp.KeyChar, Pattern(CharOpt)) Then
  36.       kp.KeyChar = ControlChars.NullChar
  37.     End If
  38.   End If
  40. End Sub
  42. Private Sub KeyPressed(ByVal sender As Object, _
  43.                        ByVal e As KeyPressEventArgs) _
  44.   Handles tb1.KeyPress
  46.   AllowChars(Options.Numeric, e)
  48. End Sub
Dec 9 '08 #4
866 512MB
I will take your comments as complements. Anyway, thank you guys for your comments : )

To madankarmukta, I was thinking about RegularExpressions 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
Dec 10 '08 #5
272 256MB
Just write a few lines to the TextChanged event that fires when the text changes.
The following is an example of alphanumeric characters.
Expand|Select|Wrap|Line Numbers
  1. Private Sub TextBox1_TextChange(sender As System.Object, e As System.EventArgs)
  2.     Dim r As New System.Text.RegularExpressions.Regex("[^A-Za-z0-9]")
  3.         Dim i As Integer
  4.         i = textbox1.SelectionStart
  5.         TextBox1.Text = r.Replace(TextBox1.Text, "")
  6.         TextBox1.SelectionStart = i
  7. End Sub
Jul 1 '21 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Sanka | last post by:
I want to restrict users entering non numeric characters in a text box How can I do this? If there is any code sample please answer or email I'll be very glad Thank you
by: anonieko | last post by:
This applies to javascript dynamic textbox onkey > > > Newsgroups: comp.lang.javascript From: Lasse Reichstein Nielsen <l...@hotpop.com> - Find messages by this author Date: Fri, 15 Jul 2005...
by: success_ny | last post by:
Does anyone have a code snippet to compare those values so I can sort the array of alpha-numeric values that include both characters and integers in it? I.e., if we have values like 4236 and...
by: Mark C | last post by:
All, Is there such a function that can strip all non alpha ( not between a-z) characters from a string? I have a function that I currently use that will strip one character at a time from a...
by: MLH | last post by:
I have a textbox on a form into which an alpha-numeric string of data is entered. I wish to force the casual user, who would sometimes use upper case, sometimes not and sometimes MIX the case -...
by: Alpha | last post by:
Hi, I have a window based applicaton. I want to make sure that the users enter integer numbers before I save it to the database. I know to code this in the textbox_validating event but I don't...
by: Itar | last post by:
I'm having a problem supressing characters in a text box. I only want alpha numeric characters (no special chars). I can handle the TextBox_KeyPress event to supress the invalid characters when...
by: ameen.abdullah | last post by:
Hi Guys, I have a textbox in windows form that should only accept alphabets, numbers, spaces and underscore. If the textbox contains anyother character it should display a msg at the time of...
by: .Net Sports | last post by:
I am checking for text input on a form validation in javascript that required at least one numeric character along with any number of alpha characters for a given input text box. The below is a var...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.