VB.net中的文本框格式

VB.net中的文本框格式,vb.net,Vb.net,我想格式化我的文本框,以便用户不能输入任何符号,例如(),;'“$%^[]{} If (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = ".")) Then e.Handled = True End if 此代码将阻止用户输入数字或整数。但如何阻止符号 提前谢谢。怎么样 Not Char.IsLetter(e.KeyChar) ?您还可以使用Ajax中的“屏蔽编辑”。可以在以

我想格式化我的文本框,以便用户不能输入任何符号,例如(),;'“$%^[]{}

If (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = ".")) Then
             e.Handled = True

End if
此代码将阻止用户输入数字或整数。但如何阻止符号

提前谢谢。

怎么样

Not Char.IsLetter(e.KeyChar)

您还可以使用Ajax中的“屏蔽编辑”。可以在以下位置找到Ajax控件工具包:

安装Ajax。按照网站上提供的有关如何将Ajax控件添加到my Visual Studio的步骤进行操作。然后,将“MaskedEditExtender”控件拖动到要格式化的文本框中

在显示“掩码”的属性字段中,我键入了(999)999-9999

在这之后,我发现我必须在设计视图中添加一个名为“TollkitScriptManager”的东西,将控件拖放到txtbox上方,这是您希望格式化的文本框。我认为您不必将任何属性更改为该属性,我相信该控件必须位于您希望格式化的文本框上方


这可能是您想要的,也可能不是您想要的,但它将允许文本框使用非常特定的格式,并强制用户仅键入数字或您选择的任何内容。这对于格式化文本框中的电话号码非常有用。

我在a中编写了一个简单的类来实现这一点。下面是VB.NET版本的代码:

Public Class TextBoxFilter
    <Flags()> Public Enum Filters
        None = 0
        Text = 1
        Numbers = 2
        AlphaNumeric = Filters.Text Or Filters.Numbers
        Currency = 4
        All = Filters.Text Or Filters.Numbers Or Filters.Currency
    End Enum

    Dim _keyFilter As Dictionary(Of TextBox, Filters)
    Dim _allowedKeys As Dictionary(Of TextBox, String)
    Dim _invalidKeys As Dictionary(Of TextBox, String)
    Dim _keyEventArgs As Dictionary(Of TextBox, Windows.Forms.KeyEventArgs)

    Private Shared DecimalMark As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private Shared NegativeMark As String = Application.CurrentCulture.NumberFormat.NegativeSign
    Private Shared CurrencySymb As String = Application.CurrentCulture.NumberFormat.CurrencySymbol
    Private Shared CurrencyDecimal As String = Application.CurrentCulture.NumberFormat.CurrencyDecimalSeparator


    Public Sub New()
        _keyFilter = New Dictionary(Of TextBox, Filters)
        _allowedKeys = New Dictionary(Of TextBox, String)
        _invalidKeys = New Dictionary(Of TextBox, String)
        _keyEventArgs = New Dictionary(Of TextBox, KeyEventArgs)
    End Sub

    'set & remove filter'

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal filter As Filters)
        SetTextBoxFilter(textBox, filter, AllowedKeys(textBox), InvalidKeys(textBox))
    End Sub

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal allowedKeys As String)
        SetTextBoxFilter(textBox, Filter(textBox), allowedKeys, InvalidKeys(textBox))
    End Sub

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, _
     ByVal allowedKeys As String, ByVal invalidKeys As String)

        SetTextBoxFilter(textBox, Filter(textBox), allowedKeys, invalidKeys)
    End Sub

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal filter As Filters, _
     ByVal allowedKeys As String, ByVal invalidKeys As String)

        If Not _keyFilter.ContainsKey(textBox) Then
            'add the textbox and its filter if it does not exist in '
            'the collection of registered textboxes                 '
            _keyFilter.Add(textBox, filter)
            _allowedKeys.Add(textBox, allowedKeys)
            _invalidKeys.Add(textBox, invalidKeys)
            _keyEventArgs.Add(textBox, New System.Windows.Forms.KeyEventArgs(Keys.None))

            'add the event handlers                                 '
            AddHandler textBox.KeyDown, AddressOf KeyDownUp
            AddHandler textBox.KeyUp, AddressOf KeyDownUp
            AddHandler textBox.KeyPress, AddressOf KeyPress
            AddHandler textBox.Validating, AddressOf Validating
            AddHandler textBox.Disposed, AddressOf Disposed

        Else
            'change the filter of the textbox if it exists in       '
            'the collection of registered textboxes                 '
            _keyFilter(textBox) = filter
            _allowedKeys(textBox) = allowedKeys
            _invalidKeys(textBox) = invalidKeys
        End If
    End Sub

    Public Sub RemoveTextBoxFilter(ByVal textBox As TextBox)
        If _keyFilter.ContainsKey(textBox) Then
            _keyFilter.Remove(textBox)
            _allowedKeys.Remove(textBox)
            _invalidKeys.Remove(textBox)
            _keyEventArgs.Remove(textBox)

            RemoveHandler textBox.KeyDown, AddressOf KeyDownUp
            RemoveHandler textBox.KeyUp, AddressOf KeyDownUp
            RemoveHandler textBox.KeyPress, AddressOf KeyPress
            RemoveHandler textBox.Validating, AddressOf Validating
            RemoveHandler textBox.Disposed, AddressOf Disposed
        End If
    End Sub

    Public Function ContainsTextBox(ByVal textBox As TextBox) As Boolean
        Return _keyFilter.ContainsKey(textBox)
    End Function

    'properties'

    Public Property Filter(ByVal textBox As TextBox) As Filters
        Get
            If ContainsTextBox(textBox) Then
                Return _keyFilter.Item(textBox)
            Else
                Return Filters.None
            End If
        End Get
        Set(ByVal value As Filters)
            SetTextBoxFilter(textBox, value)
        End Set
    End Property

    Public Property AllowedKeys(ByVal textBox As TextBox) As String
        Get
            If ContainsTextBox(textBox) Then
                Return _allowedKeys(textBox)
            Else
                Return ""
            End If
        End Get
        Set(ByVal value As String)
            SetTextBoxFilter(textBox, Me.Filter(textBox), value, Me.InvalidKeys(textBox))
        End Set
    End Property

    Public Property InvalidKeys(ByVal textBox As TextBox) As String
        Get
            If ContainsTextBox(textBox) Then
                Return _invalidKeys(textBox)
            Else
                Return ""
            End If
        End Get
        Set(ByVal value As String)
            SetTextBoxFilter(textBox, Me.Filter(textBox), Me.AllowedKeys(textBox), value)
        End Set
    End Property

    'event handlers'

    Private Sub Disposed(ByVal sender As Object, ByVal e As System.EventArgs)
        RemoveTextBoxFilter(DirectCast(sender, TextBox))
    End Sub

    Private Sub KeyDownUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        'assign the modifiers'
        _keyEventArgs(DirectCast(sender, TextBox)) = e
    End Sub

    Private Sub KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        'ensure key pressed is in the allowed keys'

        Dim txt = DirectCast(sender, TextBox)
        Dim c = e.KeyChar
        Dim allowKey As Boolean = IsValidChar(txt, c, txt.SelectionStart)


        'check for backspace & Ctrl combinations if the allowKey is still false'
        If allowKey = False Then
            If _keyEventArgs(txt).Control Then
                'control modifier goes with A, X, C, V and Z for '
                'Select All, Cut, Copy, Paste and Undo respectively'
                Dim key = _keyEventArgs(txt).KeyCode
                allowKey = (key = Keys.A OrElse key = Keys.X OrElse _
                   key = Keys.C OrElse key = Keys.V OrElse key = Keys.Z)

            ElseIf _keyEventArgs(txt).KeyCode = Keys.Back Then
                'allow the backspace key'
                allowKey = True
            End If
        End If


        'disable the key if it was not valid'
        If Not allowKey Then
            e.Handled = True
            Beep()
        End If
    End Sub

    Private Sub Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        Dim box = DirectCast(sender, TextBox)
        Dim boxFlags = _keyFilter(box)

        'skip validation if the textbox allows all entries or there is no text'
        If boxFlags = Filters.All Or box.Text = "" Then Exit Sub

        'otherwise check the characters entered'
        Dim txtChars = box.Text.ToCharArray

        Dim isValidEntry As Boolean = False

        'check each caracter for an invalid entry'
        For i = 0 To txtChars.Length - 1
            Dim c = txtChars(i)
            isValidEntry = IsValidChar(box, txtChars(i), i)

            If Not isValidEntry Then
                box.Select(i, 1)
                Exit For
            End If
        Next

        If Not isValidEntry Then e.Cancel = True

        If Not isValidEntry Then
            MsgBox("The text entered is invalid for the format " & boxFlags.ToString & "." & _
             If(_allowedKeys(box) <> "", vbCrLf & "Additional Allowed Keys: " & _allowedKeys(box), "") & _
             If(_invalidKeys(box) <> "", vbCrLf & "Additional Invalid Keys: " & _invalidKeys(box), ""), _
             MsgBoxStyle.Critical, "Invalid Entry")
        End If
    End Sub

    Private Function IsValidChar(ByVal textBox As TextBox, ByVal c As Char, ByVal charIndex As Integer) As Boolean
        'ensure key pressed is in the allowed keys '

        Dim pF = _keyFilter(textBox)
        Dim aK = _allowedKeys(textBox)
        Dim iK = _invalidKeys(textBox)
        Dim shouldAllow As Boolean = False


        'if filter is set to all, return true unconditionally '
        If pF = Filters.All Then Return True


        'check preset filters '

        'check for text '
        If EnumHasFlag(pF, Filters.Text) Then
            If Not Char.IsDigit(c) Then
                shouldAllow = True
            Else
                'if the character is a digit, check for the number flag (AlphaNumerics) '
                If EnumHasFlag(pF, Filters.Numbers) Then
                    shouldAllow = True
                End If
            End If

        End If

        'check for numbers '
        If shouldAllow = False AndAlso EnumHasFlag(pF, Filters.Numbers) Then
            If Char.IsDigit(c) Then
                shouldAllow = True
            ElseIf DecimalMark.Contains(c) Then
                'allow the decimal if there is no decimal in the textbox's
                'text or the selected text contains the mark'
                If Not textBox.Text.Contains(c) OrElse textBox.SelectedText.Contains(c) Then
                    shouldAllow = True
                End If
            ElseIf NegativeMark.Contains(c) AndAlso _
              (charindex <= NegativeMark.IndexOf(c)) Then
                'allow the negative mark if we are at the start of the'
                'textbox'
                shouldAllow = True
            End If

        End If

        'check for currency '
        If shouldAllow = False AndAlso EnumHasFlag(pF, Filters.Currency) Then
            If Char.IsDigit(c) Then
                shouldAllow = True
            ElseIf CurrencyDecimal.Contains(c) Then
                'allow the currency decimal mark if it does not exist in the '
                'textbox''s text or the selected text contains the mark '
                If Not textBox.Text.Substring(0, charIndex).Contains(c) OrElse _
                  textBox.SelectedText.Contains(c) Then
                    shouldAllow = True
                End If
            ElseIf CurrencySymb.Contains(c) AndAlso _
              (charIndex <= CurrencySymb.IndexOf(c)) Then
                'allow the currency symbol if we are in a valid position'
                shouldAllow = True
            End If

        End If



        'now check for extra allowed keys'
        If Not shouldAllow Then
            shouldAllow = aK.Contains(c)
        End If

        'and then check for extra invalid keys'
        If shouldAllow AndAlso iK.Contains(c) Then
            shouldAllow = False
        End If


        Return shouldAllow
    End Function

    <System.Diagnostics.DebuggerStepThrough()> _
     Private Function EnumHasFlag(ByVal value As [Enum], ByVal flag As [Enum]) As Boolean
        Return (Convert.ToInt64(value) And Convert.ToInt64(flag)) = Convert.ToInt64(flag)
    End Function
End Class

你可以像这样使用模式属性

 txtTel.Attributes.Add("placeholder", FormatTel.Libelle)
 txtTel.Attributes.Add("title", FormatTel.Libelle)
 txtTel.Attributes.Add("pattern", FormatTel.ExprReg)
我建议使用正则表达式。你要做的是检查用户输入的每个字符。如果字符无效,你必须用有效字符替换它们。 正则表达式模式“[^!@%&$#()*^\0-9.+-=][\]”匹配字母字符和空格。上述模式中的符号^表示与以下任何字符不匹配。符号\是一个scape字符和[]表示字符的匹配范围。如果字符串与上述模式匹配,则必须将用户输入的字符替换为有效字符

在下面的代码中,每次用户输入新字符时,都会检查用户输入是否存在无效字符

要使代码正常工作,必须导入以下命名空间:

    Imports System.Text.RegularExpressions
windows窗体的完整代码如下所示:

Imports System.Text.RegularExpressions
Public Class RegexTest
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Dim theText As String = Me.TextBox1.Text
        Dim cursor1 As Integer = Me.TextBox1.SelectionStart
        Dim cursor2 As Integer = cursor1
        Dim finalText As String = ""
        If theText IsNot Nothing AndAlso theText.Length >= 1 Then
            For x As Integer = 0 To theText.Length - 1 Step +1
                Dim Letter As String = theText.Substring(x, 1)
                Dim extStr As String = ExtractFirstString(Letter, "[^!@%&\$#\(\)\*\^\\0-9\.\+\-=\]\[_]")
                If extStr <> Letter Then
                    extStr = ""
                    finalText &= extStr
                Else
                    finalText &= Letter
                End If
            Next
        End If
        If finalText <> theText Then
            Me.TextBox1.Text = finalText
            Me.TextBox1.SelectionStart = cursor2
        End If
    End Sub


    Private Function ExtractFirstString(ByVal sourceStr As String, ByVal pattern As String) As System.String
        Dim mc As System.Text.RegularExpressions.MatchCollection
        Dim result As String = Nothing
        Dim i As Integer
        Dim brk As Boolean = False
        If sourceStr IsNot Nothing Then
            ' match email addresses!
            mc = Regex.Matches(sourceStr, pattern)
            If mc IsNot Nothing Then
                Dim results(mc.Count - 1) As String
                For i = 0 To results.Length - 1 Step +1
                    result = mc(i).Value
                    brk = True
                    Return result
                    Exit For 'only return the first match
                Next
            End If
        End If
        Return Nothing
    End Function
End Class
导入System.Text.RegularExpressions
公共类RegexTest
私有子TextBox1_TextChanged(发送者作为对象,e作为事件args)处理TextBox1.TextChanged
将文本变暗为String=Me.TextBox1.Text
Dim CURSOR 1为整数=Me.TextBox1.SelectionStart
Dim cursor2为整数=cursor1
Dim finalText As String=“”
如果文本不是空的,并且文本长度>=1,则
对于x作为整数=0到text.Length-1步长+1
作为字符串的数字字母=文本子字符串(x,1)
Dim extStr As String=ExtractFirstString(字母“[^!@%&\$\\\\\\\\\\(\)\*\^\\0-9\.\+\-=\]\[\\”)
如果你有信的话
extStr=“”
finalText&=extStr
其他的
finalText&=字母
如果结束
下一个
如果结束
如果是最后一句话,那么就放在课文后面
Me.TextBox1.Text=finalText
Me.TextBox1.SelectionStart=cursor2
如果结束
端接头
私有函数ExtractFirstString(ByVal sourceStr作为字符串,ByVal模式作为字符串)作为System.String
将mc设置为System.Text.RegularExpressions.MatchCollection
将结果设置为字符串=无
作为整数的Dim i
将brk设置为布尔值=False
如果sourceStr不是空的,那么
'匹配电子邮件地址!
mc=Regex.Matches(sourceStr,pattern)
如果mc不是什么,那么
Dim结果(mc.Count-1)作为字符串
对于i=0的结果。长度-1步+1
结果=mc(i).值
brk=True
返回结果
退出“仅返回第一个匹配项”
下一个
如果结束
如果结束
一无所获
端函数
末级

您必须在表单上创建一个名为TextBox1的文本框,并处理其TextChanged evnet。

不要忘记,如果他们复制并粘贴到文本框中,您的代码将不会拾取单个字符,因此不要仅依靠此代码进行验证。通常最好说什么是允许的,而不是什么是不允许的@klausbyskov张贴。就像俱乐部的保镖一样,不要说“不要让爱丽丝、鲍勃或查理进来……”,更容易说“这些(x)人可以进来,没有其他人”。
Imports System.Text.RegularExpressions
Public Class RegexTest
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Dim theText As String = Me.TextBox1.Text
        Dim cursor1 As Integer = Me.TextBox1.SelectionStart
        Dim cursor2 As Integer = cursor1
        Dim finalText As String = ""
        If theText IsNot Nothing AndAlso theText.Length >= 1 Then
            For x As Integer = 0 To theText.Length - 1 Step +1
                Dim Letter As String = theText.Substring(x, 1)
                Dim extStr As String = ExtractFirstString(Letter, "[^!@%&\$#\(\)\*\^\\0-9\.\+\-=\]\[_]")
                If extStr <> Letter Then
                    extStr = ""
                    finalText &= extStr
                Else
                    finalText &= Letter
                End If
            Next
        End If
        If finalText <> theText Then
            Me.TextBox1.Text = finalText
            Me.TextBox1.SelectionStart = cursor2
        End If
    End Sub


    Private Function ExtractFirstString(ByVal sourceStr As String, ByVal pattern As String) As System.String
        Dim mc As System.Text.RegularExpressions.MatchCollection
        Dim result As String = Nothing
        Dim i As Integer
        Dim brk As Boolean = False
        If sourceStr IsNot Nothing Then
            ' match email addresses!
            mc = Regex.Matches(sourceStr, pattern)
            If mc IsNot Nothing Then
                Dim results(mc.Count - 1) As String
                For i = 0 To results.Length - 1 Step +1
                    result = mc(i).Value
                    brk = True
                    Return result
                    Exit For 'only return the first match
                Next
            End If
        End If
        Return Nothing
    End Function
End Class