473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Forms TextBox + Stopping certain text

Hey All,
I am trying to make a textbox that will only allow alphanumeric values. I accomplished this by using the key pressed event, and validating the character against a regex and saying that the character is handled if the character does not match a regex.

This works great, but it breaks in one case: Pasting into the text box. How can I accomplish my goal of stopping invalid pasting into the textbox as well? I have been trying to use the text changed event, but by that point the text seems already set.

So is there a way to do this, or is there some way to check what the new text is before approving it?

Thanks!
Aug 27 '08 #1
7 1415
cloud255
427 Expert 256MB
Hey you could try to use one of the key events like below:

Expand|Select|Wrap|Line Numbers
  1. if (e.Control && e.KeyCode == Keys.V)
  2.             {
  3.                 textBox1.Text = originalText;
  4.             }
this might affect some of your other events, cant tell for sure without seeing your code.

Good luck
Aug 27 '08 #2
balabaster
797 Expert 512MB
As it would happen, I just had to do this yesterday - are you doing this in a windows application or a web application? In a windows application, you do the following:

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.         If Not Asc(e.KeyChar) = Keys.Back Then Return 'If you stop them using delete/backspace, this is really annoying, so best let those through...
  3.  
  4.         Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
  5.         If Not Regex.IsMatch(e.KeyChar, Pattern) Then
  6.             e.Handled = True 'Ignore it
  7.         End If
  8.  
  9. End Sub
You can get more complex than this too by checking the current length of the text, say for instance, when they're entering a postal code in Canada which requires the following pattern [A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]

By checking the current length, you could change the pattern of allowable chars, if the length is 0, only allow alphas, if the length is 1 only allow digits etc. If the length is 2, only allow alphas, automatically add a space after the entered char and then only allow numerics again.

I used this method to only allow validly formatted variable names into a text box for an expression builder I'm writing (make sure to import System.Text.RegularExpressions):

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.  
  3.     Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
  4.  
  5.     If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
  6.  
  7.     Dim Pattern As String = Nothing
  8.     If (txtObj.Text.Length = 0) Then
  9.         Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
  10.     Else
  11.         Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
  12.     End If
  13.  
  14.     If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
  15.  
  16. End Sub
Aug 27 '08 #3
As it would happen, I just had to do this yesterday - are you doing this in a windows application or a web application? In a windows application, you do the following:

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.         If Not Asc(e.KeyChar) = Keys.Back Then Return 'If you stop them using delete/backspace, this is really annoying, so best let those through...
  3.  
  4.         Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
  5.         If Not Regex.IsMatch(e.KeyChar, Pattern) Then
  6.             e.Handled = True 'Ignore it
  7.         End If
  8.  
  9. End Sub
You can get more complex than this too by checking the current length of the text, say for instance, when they're entering a postal code in Canada which requires the following pattern [A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]

By checking the current length, you could change the pattern of allowable chars, if the length is 0, only allow alphas, if the length is 1 only allow digits etc. If the length is 2, only allow alphas, automatically add a space after the entered char and then only allow numerics again.

I used this method to only allow validly formatted variable names into a text box for an expression builder I'm writing (make sure to import System.Text.RegularExpressions):

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.  
  3.     Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
  4.  
  5.     If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
  6.  
  7.     Dim Pattern As String = Nothing
  8.     If (txtObj.Text.Length = 0) Then
  9.         Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
  10.     Else
  11.         Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
  12.     End If
  13.  
  14.     If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
  15.  
  16. End Sub
This is what I have done and working. The problem is, if you copy and paste invalid data into the text box, it allows it, and it breaks the validation. I'm trying to figure out how to stop that scenario.
Aug 27 '08 #4
balabaster
797 Expert 512MB
As it would happen, I just had to do this yesterday - are you doing this in a windows application or a web application? In a windows application, you do the following:

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.         If Not Asc(e.KeyChar) = Keys.Back Then Return 'If you stop them using delete/backspace, this is really annoying, so best let those through...
  3.  
  4.         Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
  5.         If Not Regex.IsMatch(e.KeyChar, Pattern) Then
  6.             e.Handled = True 'Ignore it
  7.         End If
  8.  
  9. End Sub
You can get more complex than this too by checking the current length of the text, say for instance, when they're entering a postal code in Canada which requires the following pattern [A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]

By checking the current length, you could change the pattern of allowable chars, if the length is 0, only allow alphas, if the length is 1 only allow digits etc. If the length is 2, only allow alphas, automatically add a space after the entered char and then only allow numerics again.

I used this method to only allow validly formatted variable names into a text box for an expression builder I'm writing (make sure to import System.Text.RegularExpressions):

Expand|Select|Wrap|Line Numbers
  1. Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
  2.  
  3.     Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
  4.  
  5.     If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
  6.  
  7.     Dim Pattern As String = Nothing
  8.     If (txtObj.Text.Length = 0) Then
  9.         Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
  10.     Else
  11.         Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
  12.     End If
  13.  
  14.     If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
  15.  
  16. End Sub
In a web application, you obviously have to do this client side... beware though, a user can bypass this by turning off javascript, so be aware, that it must be validated on the postback by server side code by checking the whole string for validity (if that's even a word)...

As it happens, the javascript code isn't a world different than the windows application code:

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.   var tb = document.getElementById("TextBoxElementID");
  3.  
  4.   tb.keydown = function(event)
  5.   {
  6.     var evt = event || window.event;
  7.     var char = String.fromCharCode(evt.keyCode);
  8.     var allowChars;
  9.     if(this.text.length = 0)
  10.     {
  11.       allowChars = "[_a-zA-Z]";
  12.     }
  13.     else
  14.     {
  15.       allowChars = "[_a-zA-Z0-9]";
  16.     }
  17.     var re = new RegExp(allowChars);
  18.     if(!re.test(char))
  19.     {
  20.       evt.returnValue = null;
  21.     }
  22. }
  23. </script>
Aug 27 '08 #5
balabaster
797 Expert 512MB
This is what I have done and working. The problem is, if you copy and paste invalid data into the text box, it allows it, and it breaks the validation. I'm trying to figure out how to stop that scenario.

Hmm, I hadn't thought of that... what I would probably do in that case is set the ShortcutsEnabled property of the textbox to false.

I'm not sure what version of .NET this property was included, it may not be there in earlier versions than 2008. However, you can neatly sidestep the situation by replacing the context menu for the textbox object with a blank context menu, thus removing the right click ability to paste via the context menu, and catch the key combinations for CTRL+V or SHIFT+INS and cancel them rendering them useless and hence turning off the ability to paste into the textbox.
Aug 27 '08 #6
Hmm, I hadn't thought of that... what I would probably do in that case is set the ShortcutsEnabled property of the textbox to false.

I'm not sure what version of .NET this property was included, it may not be there in earlier versions than 2008. However, you can neatly sidestep the situation by replacing the context menu for the textbox object with a blank context menu, thus removing the right click ability to paste via the context menu, and catch the key combinations for CTRL+V or SHIFT+INS and cancel them rendering them useless and hence turning off the ability to paste into the textbox.
Here is how I was able to handle it. Just got it working:

If the regex doesn't match, then set the text to the original text.

If the regex matches, allow it, and save the original text as the current text. Basically, you just keep the previous text as an instance variable, and revert back when you need to.
Aug 27 '08 #7
balabaster
797 Expert 512MB
Here is how I was able to handle it. Just got it working:

If the regex doesn't match, then set the text to the original text.

If the regex matches, allow it, and save the original text as the current text. Basically, you just keep the previous text as an instance variable, and revert back when you need to.
Yep, I guess that would do the job too... the marvelous thing about programming is there are many ways to skin a cat.
Aug 27 '08 #8

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

Similar topics

5
by: Armando | last post by:
I recently saw the tail end of a "Continuous forms" discussion, but not enough was available to see if this will be a PITA repeat question. Sorry if it is. On a form with its Default View...
3
by: Kris van der Mast | last post by:
Hi, I've created a little site for my sports club. In the root folder there are pages that are viewable by every anonymous user but at a certain subfolder my administration pages should be...
7
by: Mike Bulava | last post by:
I have created a base form that I plan to use throughout my application let call the form form1. I have Built the project then add another form that inherits from form1, I add a few panel controls...
15
by: Joshua Kendall | last post by:
I have a script in which it keeps opening the same form instead of only one instance. I also need help with a form that has a password. Where do I put the actual password? can I use a database for...
3
by: Rvo | last post by:
I have a userform which contains a textbox (System.Windows.forms.textbox) with multiline set to True. This box contains a certain number of characters which reach below the bottom of the box....
1
by: Aaron Smith | last post by:
I am creating a subclassed text box. I want to have a button inside the tetbox. That was the easy part. The part I can't figure out, is how you set the area for the text? If you type a string it...
3
by: DotNetNewbie | last post by:
I am reading the book Teach Yourself Microsoft Visual Basic .Net 2003 in 21 Days. I am having trouble getting one of the exercises to work at the end of day 4. Exercises: 1. Create a new...
10
by: garyusenet | last post by:
I have a multiline textbox. The size of the text box should be 75 characters wide, and 5 lines in height like this: - <---75 characters--> <---75 characters--> <---75 characters--> <---75...
14
by: > Adrian | last post by:
Is there a way of stopping text from highlighting in textbox? Many thanks, Adrian.
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.