473,396 Members | 2,002 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

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

lotus18
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
  1.  
  2. Public Enum MyOption
  3.         Alpha = 1
  4.         AlphaNumeric = 2
  5.         Numeric = 3
  6.     End Enum
  7.  
  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
  37.  
  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 28484
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
madankarmukta
308 256MB
HI,

Make use of Regular Expressiona.

Thanks!
Dec 9 '08 #3
balabaster
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
  6.  
  7. Function Pattern(ByVal CharOpt As Options)
  8.  
  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
  18.  
  19.   'All my patterns allow spaces... 
  20.   Return String.Format("[{0}\s]", s)
  21.  
  22. End Function
  23.  
  24. Public Sub AllowChars(ByVal CharOpt As Options, _
  25.                       ByVal kp As KeyPressEventArgs)
  26.  
  27.   'Create list of always allowable keys
  28.   Dim Allow As Keys() = {Keys.Delete, Keys.Back}
  29.  
  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
  39.  
  40. End Sub
  41.  
  42. Private Sub KeyPressed(ByVal sender As Object, _
  43.                        ByVal e As KeyPressEventArgs) _
  44.   Handles tb1.KeyPress
  45.  
  46.   AllowChars(Options.Numeric, e)
  47.  
  48. End Sub
Dec 9 '08 #4
lotus18
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
SioSio
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

2
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
2
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...
3
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...
6
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...
8
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 -...
4
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...
7
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...
5
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...
8
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.