0

i want to allow only alphanumeric password i have written following code to match the same but the same is not working

Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") never return false even if i type password test(which do not contain any number).

ElseIf Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") = False Then
 div_msg.Attributes.Add("class", "err-msg")
 lblmsg.Text = "password is incorrect"

I have tried this also
Dim r As New Regex("^[a-zA-Z0-9]+$")
Dim bool As Boolean
bool = r.IsMatch(txtpassword.Text) and for txtpassword.Text = '4444' , bool is coming true i dont know what is wrong.
sergioramosiker
  • 385
  • 3
  • 5
  • 21

3 Answers3

1

First of all, the '_' is not a valid alpha-numeric character. See http://en.wikipedia.org/wiki/Alphanumeric

And, second, take another look at your regular expression.

[a-zA-Z0-9_]*

This can match 0 OR more alpha-numeric characters or 0 OR more '_' characters. Using this pattern, a password '&#&#^$' would return TRUE.

You probably want to test for 1 OR more characters that ARE NOT an alpha-numeric. If that test returns TRUE, then throw the error.

Hope this helps.

DTH
  • 11
  • 2
1

Try the following Expression:

([^a-zA-Z0-9]+)

This will match if your Password contains any character that is not alphanumeric. If you get a match, do your error handling.

Merlin Denker
  • 1,380
  • 10
  • 15
  • hi, i tried the following code If Regex.IsMatch(txtpassword.Text, "([^a-zA-Z0-9]+)") = False Then div_msg.Attributes.Add("class", "err-msg") lblmsg.Text = "password is incorrect" but for password 455tt it is still not working – sergioramosiker Feb 26 '14 at 16:03
  • If the IsMatch of this Pattern returns False, that means no invalid characters are found. So basically you're now saying "password is incorrect" only when the password is valid... Just remove the "= False" and you will be fine – Merlin Denker Feb 28 '14 at 09:09
1

So based on the Regex that you have in the question, it appears you want a password with one lower-case and upper-case letter, one number, and an _; so here is a Regex that will do that:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*_).{4,8}

Regular expression visualization

Debuggex Demo

The {4,8} indicates the length of the password; you can set that accordingly.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232