Rafael Enriquez
Rafael Enriquez

Reputation: 333

Problem with an asp net password regular expression?

I'm trying to validate the following in a password field:
-at least 1 alpha
-at least 1 numeric
-at least 1 special (non alphanumeric)

My reg exp is this:

Regex.IsMatch("jpere33z@1?hs", @"^\w*(?=\w*\d)(?=\w*[a-z])(?=\W*)\w*$")  

and it says it is not valid. The \W part is what is not working.

Could you please tell me why?

Upvotes: 0

Views: 134

Answers (3)

agent-j
agent-j

Reputation: 27923

\w*$ will only match letters, numbers, and underscore. This is what you want:

Regex.IsMatch("@1?hsjpere33z", @"^(?=.*?\d)(?=.*?[a-z])(?=.*?\W).*$", RegexOptions.IgnoreCase)

I moved the validation to the left, and added \w* right before the \W. Edit: Also used .* instead of \w for test lookaheads.

Upvotes: 2

SJuan76
SJuan76

Reputation: 24885

This is difficult to do with regex (at least only one). In the regex you are giving the fields an order, so the parser expects them in that order.

One alternative would be to use a choice, but that would make difficult to check that you have one of each of the terms:

[\w|\d|\W]{4,}

If you want to use regex, check three of them:

1) Is there a digit?

2) Is there a character?

3) Is there a special?

If all of them are true.... bingo!

Upvotes: 0

Variant
Variant

Reputation: 17365

Your regex doesn't allow more then 1 digit.

Your easiest route would probably be to have 3 regex checks, one for the existance of each character type.

Upvotes: 0

Related Questions