Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Go Back  Xtreme Visual Basic Talk > > > Prevent User from using certain chars in textbox


Reply
 
Thread Tools Display Modes
  #1  
Old 04-29-2010, 09:28 AM
Revel20 Revel20 is offline
Newcomer
 
Join Date: Sep 2009
Posts: 14
Default Prevent User from using certain chars in textbox


Hello, I have a Textbox in which the user types in a name for a folder to be created. However, Windows does not allow the followin chars:

\ / * : ? " <> |

When you try to change the name of any folder a tooltip ballon pops up forbidding the user to write, or paste, such a char.

My question is, how can I make the exact tooltip ballon appear in my TextBox?

Thanks in advance

Revel
Reply With Quote
  #2  
Old 04-29-2010, 10:20 AM
phb2911's Avatar
phb2911 phb2911 is offline
Regular
 
Join Date: Mar 2009
Location: Manville, NJ USA
Posts: 54
Default

Use the text box's KeyDown event to validate the user input, if it is one of the forbidden chars display the tooltip balloon and set e.SuppressKeyPress = true.
Reply With Quote
  #3  
Old 04-29-2010, 12:12 PM
Revel20 Revel20 is offline
Newcomer
 
Join Date: Sep 2009
Posts: 14
Default

great idea, hadn't thought about that. Thanks!
Reply With Quote
  #4  
Old 04-29-2010, 02:15 PM
celtic celtic is offline
Centurion
 
Join Date: Mar 2009
Posts: 132
Default ...an example

(Allows only numeric and backspace (and arrow keys work by default))

Code:
Select Case e.KeyChar
            Case "0" To "9"
                ' Do nothing
            Case vbBack
                ' Do nothing
            Case Else
                e.Handled = True
End Select
Reply With Quote
  #5  
Old 04-29-2010, 03:15 PM
PlausiblyDamp's Avatar
PlausiblyDampPrevent User from using certain chars in textbox PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

You might find it easier to create your own control and reuse the logic rather than dealing with it on a case by case basis. http://www.xtremedotnettalk.com/showthread.php?t=96003 is a sample I wrote a while ago that might be of use.
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #6  
Old 04-29-2010, 08:29 PM
Revel20 Revel20 is offline
Newcomer
 
Join Date: Sep 2009
Posts: 14
Default

I would like to see that sample, but I just can't download it, I'm logged in, and it asks for my info to log in again, but an error pops saying that the info entered is not correct, dunno what's happening...
Reply With Quote
  #7  
Old 05-01-2010, 04:56 AM
PlausiblyDamp's Avatar
PlausiblyDampPrevent User from using certain chars in textbox PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

Will check to see if there is a problem with your account over there, I have attached to relevant class here though.
Code:
Option Strict On

Imports System.ComponentModel

Public Class RestrictedTextBox
    Inherits TextBox

    'Tracks the allowed control content
    Private _allowedContent As AllowedContentTypes = AllowedContentTypes.Any

    'Event to raise when invalid content is attempted
    Public Delegate Sub InvalidKeystrokeEventHandler(ByVal sender As Object, ByVal e As RestrictedTextBoxEventArgs)
    Public Event InvalidKeystroke As InvalidKeystrokeEventHandler

    'Enumeration of valid content types, use the Flags() attribute
    'as this allows combinations to be defined.
    <Flags()> _
    Public Enum AllowedContentTypes
        Alphabetic = 1
        Numeric = 2
        Alphanumeric = 3
        Punctuation = 4
        PunctuatedAlphabetic = 5
        Separators = 8
        Symbols = 16
        Any = 31
        AllowCustom = 32
        DenyCustom = 64
    End Enum

    Private _customCharacters As String

    <Description("Valid list of characters the control can contain, used when allowed content types is set to custom")> _
    Public Property CustomCharacters As String
        Get
            Return _customCharacters
        End Get
        Set(ByVal value As String)
            _customCharacters = value
        End Set

    End Property

    'IDE Stuff
    <Description("Defines the type of content the control can contain"), _
    Category("Behavior"), DefaultValue(GetType(AllowedContentTypes), "Any")> _
    Public Property AllowedContent() As AllowedContentTypes
        Get
            Return _allowedContent
        End Get
        Set(ByVal Value As AllowedContentTypes)
            _allowedContent = Value
        End Set
    End Property

    'Handle the event raising in one place...
    Protected Sub OnInvalidKeystroke(ByVal e As RestrictedTextBoxEventArgs)
        RaiseEvent InvalidKeystroke(Me, e)
    End Sub

    'when a key is pressed check if it should be allowed or not.
    Private Sub RestrictedTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        'Don't interfere with control codes (ctrl+v etc)
        If Char.IsControl(e.KeyChar) Then Return

        'Is this a valid character for the given content types
        If ValidateCharacter(e.KeyChar) Then Return

        'If keystroke hasn't been approved above then raise our event and 
        'prevent further processing of the keystroke.
        OnInvalidKeystroke(New RestrictedTextBoxEventArgs(e.KeyChar, _allowedContent))
        e.Handled = True
    End Sub

    Private Function ValidateCharacter(ByVal c As Char) As Boolean
        'Flags behaves 'oddly' with VB as it doesn't have different boolean and
        'bitwise operators so we need to convert the enum to an integer...
        Dim ac As Integer = Convert.ToInt32(_AllowedContent)

        'Possibly not the most optimal way to do this but clearer than a large OrElse list.
        'If this does appear to be a performance issue then it can be altered
        'Also just relies on the built in framework to determine character type - this means
        'is should also be region aware.
        If (ac And AllowedContentTypes.AllowCustom) > 0 AndAlso _allowedCharacters.Contains(c) Then Return True
        If (ac And AllowedContentTypes.DenyCustom) > 0 AndAlso Not _allowedCharacters.Contains(c) Then Return True

        If (ac And AllowedContentTypes.Numeric) > 0 AndAlso Char.IsNumber(c) Then Return True
        If (ac And AllowedContentTypes.Alphabetic) > 0 AndAlso Char.IsLetter(c) Then Return True
        If (ac And AllowedContentTypes.Punctuation) > 0 AndAlso Char.IsPunctuation(c) Then Return True
        If (ac And AllowedContentTypes.Separators) > 0 AndAlso Char.IsSeparator(c) Then Return True
        If (ac And AllowedContentTypes.Symbols) > 0 AndAlso Char.IsSymbol(c) Then Return True

        Return False
    End Function

    'Need to override the Text property, Get is fine but we have the possibility
    'of people trying to assign invalid text via code so alter the Set part.
    Public Overrides Property Text() As String
        Get
            Return MyBase.Text
        End Get
        Set(ByVal value As String)
            If ValidateString(value) Then
                MyBase.Text = value
            End If
        End Set
    End Property

    'Really lame function to check the validity of a string, simply loops through
    'each character till it finds an invalid one or reaches the end...
    Private Function ValidateString(ByVal data As String) As Boolean

        For Each c As Char In data
            If ValidateCharacter(c) = False Then Return False
        Next

        Return True
    End Function

    'Another possible issue is people using Paste to enter invalid text, so we
    'trap the relevant windows message and handle accordingly
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

        Const WM_PASTE As Integer = &H302

        Select Case m.Msg
            Case WM_PASTE
                ' Only interested if there is text based data so check that 1st
                If Clipboard.GetDataObject.GetDataPresent(DataFormats.Text, True) Then
                    'If it is text, retrieve it and validate it
                    Dim tmp As String = Clipboard.GetDataObject.GetData(DataFormats.Text, True).ToString

                    'If valid perform the paste
                    If ValidateString(tmp) Then
                        MyBase.WndProc(m)
                    End If
                End If
            Case Else
                'All other messages get dealt with by the default handler...
                MyBase.WndProc(m)
        End Select

    End Sub
End Class

'EventArgs clas for InvalidKeystroke event
Public Class RestrictedTextBoxEventArgs
    Inherits EventArgs

    Private _char As Char
    Private _allowedContent As RestrictedTextBox.AllowedContentTypes

    'Allow the handler to retreive the invalid character
    Public ReadOnly Property InvalidCharacter() As Char
        Get
            Return _char
        End Get
    End Property

    'Return the allowed content types.
    Public ReadOnly Property AllowedContent() As RestrictedTextBox.AllowedContentTypes
        Get
            Return _allowedContent
        End Get
    End Property

    'constructor
    Public Sub New(ByVal invalidCharacter As Char, ByVal allowedContent As RestrictedTextBox.AllowedContentTypes)
        _char = invalidCharacter
        _allowedContent = allowedContent
    End Sub

End Class
If you create a Windows control library project and add this class to it you should then be able to add the control to your toolbar.

There is a property called AllowedContent that you can select in the designer to choose what to allow, if you need to provide a list of specific characters then choose DenyCustom as the type and provide the list of disallowed characters for the CustomCharacters property. This will disallow those characters when typing and will also raise an event you can handle to display tooltips etc.

The control will also validate any attempt to assign a string to the .Text property and also handles attempts to paste invalid data as well.
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #8  
Old 05-10-2010, 12:52 PM
Ambassa Ambassa is offline
Newcomer
 
Join Date: May 2010
Posts: 4
Default

Anyone else got a simpler solution? =)
Reply With Quote
  #9  
Old 05-10-2010, 07:27 PM
Roger_Wgnr's Avatar
Roger_Wgnr Roger_Wgnr is offline
CodeASaurus Hex

Forum Leader
* Expert *
 
Join Date: Jul 2006
Location: San Antonio TX
Posts: 2,427
Default

Why not use something like this
Code:
    Public Function IsPathValid(ByVal ThePathToCheck As String) As Boolean
        Dim invalidCharArray() As Char = System.IO.Path.GetInvalidPathChars
        For Each entry As Char In invalidCharArray
            If ThePathToCheck.Contains(entry.ToString) Then
                Return False
            End If
        Next
        Return True
    End Function
then just call the function in the validate event and show a messagebox if it is invalid.
__________________
Code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. ~Martin Golding
The user is a peripheral that types when you issue a read request. ~Peter Williams
MSDN Visual Basic .NET General FAQ
Reply With Quote
  #10  
Old 05-11-2010, 09:52 AM
AtmaWeapon's Avatar
AtmaWeaponPrevent User from using certain chars in textbox AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

All you have to do is copy PlausiblyDamp's code and paste it as a new class in your project, and you're done. There's one error that is easy to figure out: _allowedCharacters inside of ValidateCharacters should be _customCharacters instead.

Restricting input in a text box is *not* something that can be done in just a couple of lines of code. The easy case is "ignore certain keys when the user pushes them". That can be easily done with a handler for keypress events. But there's four other ways text can enter the control:
  1. The user can paste text.
  2. The user can use character shortcuts.
  3. The programmer can set the Text property.
  4. Someone can write a script that sends EM_SETTEXT to set the text.

Case 1 is handled about as well as you can handle it in PlausiblyDamp's example. There's no event that tells you a paste is being performed, so you have to override WndProc() and look for a WM_PASTE message, examine the clipboard data, and reject invalid clipboard data. I might add some code to indicate that the paste was rejected, but that's irrelevant.

I thought case 2 was more difficult, but it's handled the same way as case 1. The user can hold down ALT and push numbers on the number pad to insert characters. Turns out this manifests a KeyPress event for the character it represents, so handling case 1 fixes it.

Cases 3 and 4 require you to override and guard the Text property and reject invalid values. Again, I think it would be nice to indicate that it was rejected rather than do nothing.

I was going to implement a control with *just* the required functionality, but there's no point. You've got something that works above and beyond the requirements and instructions for using the control. I don't think it can get any less complicated.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #11  
Old 05-11-2010, 10:08 AM
PlausiblyDamp's Avatar
PlausiblyDampPrevent User from using certain chars in textbox PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

Quote:
Originally Posted by AtmaWeapon View Post
All you have to do is copy PlausiblyDamp's code and paste it as a new class in your project, and you're done. There's one error that is easy to figure out: _allowedCharacters inside of ValidateCharacters should be _customCharacters instead.
Oops, teach me to copy and hack code in notepad rather than in VS. I've attached a fixed version to this post.

Quote:
Originally Posted by AtmaWeapon View Post
Cases 3 and 4 require you to override and guard the Text property and reject invalid values. Again, I think it would be nice to indicate that it was rejected rather than do nothing.
The control raises an event on invalid characters (technically one per invalid character - I only did this as a sample and never bothered to handle multiple characters properly) so rejection can at least be spotted.
Attached Files
File Type: vb RestrictedTextBox.vb (6.5 KB, 29 views)
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #12  
Old 06-29-2010, 02:13 AM
Hypernova Hypernova is offline
Newcomer
 
Join Date: Jun 2010
Location: Sweden
Posts: 7
Smile More than one?

If I want the user to be able to use just one comma, and restrict him/her for using two or more, how am I supposed to do then? And i also wonder if i could make commas make the same thing as dots
, = .
is it possible?
Reply With Quote
  #13  
Old 06-29-2010, 02:18 AM
Hypernova Hypernova is offline
Newcomer
 
Join Date: Jun 2010
Location: Sweden
Posts: 7
Default

Quote:
Originally Posted by Hypernova View Post
If I want the user to be able to use just one comma, and restrict him/her for using two or more, how am I supposed to do then? And i also wonder if i could make commas make the same thing as dots
, = .
is it possible?
Just solved the single or double comma thingy with this code, maybe not the best one but I want to show you and maybe I could improve it or so?

If e.KeyChar = "," Then
If TextBox1.Text.IndexOf(",") > -1 Then
e.Handled = True
End If
ElseIf Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
Select Case e.KeyChar
Case "0" To "9"
' Do nothing
Case vbBack
' Do nothing
Case ","
' Do nothing
Case Else
e.Handled = True
End Select
Reply With Quote
Reply

Tags
custom control, ducks, prevent, strawberries, textbox, tooltip, user, wm_paste, \ / * : ? " <> |


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
 
Prevent User from using certain chars in textbox
Prevent User from using certain chars in textbox
 
-->