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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27126257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:31:17  来源:igfitidea点击:

VB.Net Validation: Checking if Text Contains Only Letters

regexvb.netstringvalidation

提问by Jason

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”之类的。

回答by Alex K.

Use a Regular Expression

使用正则表达式

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

Edit

编辑

The ^ $character are anchors; they mean match the startand end-of-linerespectively and can be used to prevent sub-string/partial matches.

^ $角色是; 它们意味着匹配开始结束时的线分别和可用于防止子串/部分匹配。

E.g. The regex Xwould 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>"

回答by Justin Ryan

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

回答by Missing_Link

To make it simple:

为了简单起见:

Char.isletter(textboxname)

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

回答by rory.ap

You can use a regular expression, like this:

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

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