过滤哪些字符可以添加到文本框中 [英] FIltering what characters can be added to a text box
问题描述
我的表单上有一系列文本框,我的客户希望我过滤掉不允许的字符,例如在name
字段中不能有符号或数字.
I have a series of text boxes on my form, and my client wants me to filter out characters that aren't allowed, for example in the name
field you cannot have symbols or numbers.
现在,他想要它,因此当您尝试输入特殊字符时,它根本不会输入到文本框中.我对此很了解,但是我不确定如何编码.
Now, he wants it so when you try and put in a special character it simply will not get entered into the text box. I know the logistics to this, but I'm not sure how I would go about coding it.
基本上需要发生的是,当用户键入诸如$, ^, 5, *
之类的字符时,函数需要识别该字符并阻止其输入文本框,这意味着它们一旦进入即被删除或中断整个动作.
Basically what needs to happen is when the user types in characters like $, ^, 5, *
etc, a function needs to recognise this and stop them from being entered into the textbox, whether it means deleting them as soon as they go in or interrupting the action altogether.
有人对此有一些见识吗?谢谢,谢谢.
Anybody have some insight into this? Anything is appreciated, thanks.
推荐答案
您可以使用正则表达式:
You could use a regex:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
StripNonAlphabetCharacters(TextBox1)
End Sub
Public Sub StripNonAlphabetCharacters(ByVal input As TextBox)
' pattern matches any character that is NOT A-Z (allows upper and lower case alphabets)
Dim rx As New Regex("[^a-zA-Z]")
If (rx.IsMatch(input.Text)) Then
Dim startPosition As Integer = input.SelectionStart - 1
input.Text = rx.Replace(input.Text, "")
input.SelectionStart = startPosition
End If
End Sub
实际的Regex
应该成为表单的成员,因此不必每次都声明它或将其放入某个通用类中以供参考.选择逻辑用于在删除无效字符后将光标保持在其当前位置.
The actual Regex
ought to be made a member of the form so it isn't declared each time or placed into some common class for reference. The selection logic is used to keep the cursor at its current location after stripping the invalid characters.
对于WinForms,您可以使用 MaskedTextBox类并设置面具属性.
For WinForms you can use the MaskedTextBox Class and set the Mask property.
对于ASP.NET,您可以使用AJAX工具包的 MaskedEdit控件.
For ASP.NET you could use the AJAX Toolkit's MaskedEdit control.
这篇关于过滤哪些字符可以添加到文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!