简体   繁体   English

VB.Net验证:检查文本是否仅包含字母

[英]VB.Net Validation: Checking if Text Contains Only Letters

Need to know how to validate a Text Box's text to make sure it contains ONLY letters without spaces. 需要知道如何验证文本框的文本,以确保其仅包含字母且没有空格。

I was hoping some sort of functions exists which could help me, something like "IsString" or something. 我希望存在某种可以帮助我的函数,例如“ IsString”之类的东西。

Use a Regular Expression 使用正则表达式

if System.Text.RegularExpressions.Regex.IsMatch(TextBox.Text, "^[A-Za-z]+$")) ...

Edit 编辑

The ^ $ character are anchors ; ^ $字符是锚点 they mean match the start and end-of-line respectively and can be used to prevent sub-string/partial matches. 它们的意思是分别匹配行的开始结尾,并且可以用来防止子字符串/部分匹配。

Eg The regex X would match "X" and "AAAXAAA" but ^X$ only matches "X" as its value can be thought of as "<start of line>X<end of line>" 例如,正则表达式X将匹配"X""AAAXAAA"但是^X$仅匹配"X"因为它的值可以被认为是"<start of line>X<end of line>"

This will prevent anything from being typed into the TextBox except letters. 这将防止除了字母之外的任何内容都键入到TextBox中。

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsLetter(e.KeyChar) Then e.Handled = True  'ignore everything but letter keys
End Sub

您可以使用正则表达式,如下所示:

Return (New System.Text.RegularExpressions.Regex("^[a-zA-Z]{1,}$")).IsMatch(testValue)

To make it simple: 为了简单起见:

Char.isletter(textboxname)

If char.isletter(textboxname)=false then
Msgbox(error message)
Textboxname.clear()
Textboxname.focus()
End if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM