Jason
Jason

Reputation: 47

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.

Upvotes: 2

Views: 20140

Answers (4)

Missing_Link
Missing_Link

Reputation: 1

To make it simple:

Char.isletter(textboxname)

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

Upvotes: 0

Alex K.
Alex K.

Reputation: 175766

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.

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

Upvotes: 5

Justin Ryan
Justin Ryan

Reputation: 1404

This will prevent anything from being typed into the TextBox except letters.

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

Upvotes: 2

rory.ap
rory.ap

Reputation: 35260

You can use a regular expression, like this:

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

Upvotes: 0

Related Questions