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!
7 1415
Hey you could try to use one of the key events like below: - if (e.Control && e.KeyCode == Keys.V)
-
{
-
textBox1.Text = originalText;
-
}
this might affect some of your other events, cant tell for sure without seeing your code.
Good luck
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: - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
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...
-
-
Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then
-
e.Handled = True 'Ignore it
-
End If
-
-
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): - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
-
Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
-
-
If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
-
-
Dim Pattern As String = Nothing
-
If (txtObj.Text.Length = 0) Then
-
Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
-
Else
-
Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
-
End If
-
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
-
-
End Sub
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: - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
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...
-
-
Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then
-
e.Handled = True 'Ignore it
-
End If
-
-
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): - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
-
Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
-
-
If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
-
-
Dim Pattern As String = Nothing
-
If (txtObj.Text.Length = 0) Then
-
Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
-
Else
-
Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
-
End If
-
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
-
-
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.
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: - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
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...
-
-
Dim Pattern = "[_a-zA-Z]" 'Pattern of allowable chars
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then
-
e.Handled = True 'Ignore it
-
End If
-
-
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): - Private Sub VarNameKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtVarName.KeyPress
-
-
Dim txtObj As TextBox = CType(Sender, Textbox) 'Get the textbox
-
-
If Asc(e.KeyChar) = Keys.Back Then Return 'Allow the user to delete
-
-
Dim Pattern As String = Nothing
-
If (txtObj.Text.Length = 0) Then
-
Pattern = "[_a-zA-Z]" 'The first char must be an _ or an alpha
-
Else
-
Pattern = "[_a-zA-Z0-9]" 'The remaining chars can be _ or alphanumeric
-
End If
-
-
If Not Regex.IsMatch(e.KeyChar, Pattern) Then e.Handled = True 'Ignore It
-
-
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: - <script type="text/javascript">
-
var tb = document.getElementById("TextBoxElementID");
-
-
tb.keydown = function(event)
-
{
-
var evt = event || window.event;
-
var char = String.fromCharCode(evt.keyCode);
-
var allowChars;
-
if(this.text.length = 0)
-
{
-
allowChars = "[_a-zA-Z]";
-
}
-
else
-
{
-
allowChars = "[_a-zA-Z0-9]";
-
}
-
var re = new RegExp(allowChars);
-
if(!re.test(char))
-
{
-
evt.returnValue = null;
-
}
-
}
-
</script>
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.
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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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....
|
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...
|
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...
|
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...
|
by: > Adrian |
last post by:
Is there a way of stopping text from highlighting in textbox?
Many thanks,
Adrian.
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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...
|
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...
|
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...
|
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...
| |