yodatom10
yodatom10

Reputation: 15

Check string for a-z Visual basic

I'm trying to verify if a string contains at least one character from a-z or A-Z. I have written this code to attempt to verify but if "dog" is entered into "strpassword" it still returns false. I am new at visual basic and sure I am missing something stupid.

        If strpassword Like "[*a-z]" Then
            lbloutput.Text = strpassword
            bolpasswordchk = True
        Else
            MessageBox.Show("Password must contain a letter", "Input error")
        End If

Upvotes: 0

Views: 2653

Answers (2)

Giulio Caccin
Giulio Caccin

Reputation: 3052

The simple solution to your problem is:

If strpassword.Any(Function(c) Char.IsLetter(c)) Then
    lbloutput.Text = strpassword
    bolpasswordchk = True
Else
    MessageBox.Show("Password must contain a letter", "Input error")
End If

With this you only check your assumption: "at least one character". This solution does not use the VB only operator LIKE and let you focus on learning.

Please remember to check null or empty strings if you use my solution.

@nunzabar answer is more suited to "from a-z or A-Z" problem, but with my solution you can accept non letters.

Upvotes: 0

mr_plum
mr_plum

Reputation: 2437

Moving the wildcard character outside the bracket helps:

"*[a-z]"

But that only returns True if the password ends in lower-case letters.

To match "at least 1 character a - Z", you need:

"*[a-zA-Z]*"

This mean starting with zero or more characters (*), followed by an English letter ([a-zA-Z]), and ending with zero or more additional characters (*).

Upvotes: 1

Related Questions