过滤可以添加到文本框中的字符 [英] FIltering what characters can be added to a text box

查看:17
本文介绍了过滤可以添加到文本框中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单上有一系列文本框,我的客户希望我过滤掉不允许使用的字符,例如在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆