Eric
Eric

Reputation: 3

Combining multiple RegEx expressions to restrict passwords

I have a need to put a RegEx expression over a property in a model on a MVC website that I'm working on.

The different pieces of the expression make sense to me individually, but I can't figure out how to form them together.

I need to be able to restrict input to letters, capital letters, numbers, and the symbols @ . _ -

I then need to ensure that the following criteria is met by the user's input

  1. Input must contain 1 capital letter
  2. Input must contain 1 lowercase letter
  3. Input must contain 1 number
  4. Input must contain one of the 4 symbols that are permitted.

I've tried

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

But it ends up letting the password not include one of the 4 symbols.

Upvotes: 0

Views: 129

Answers (2)

Sayu Sekhar
Sayu Sekhar

Reputation: 169

You need to escape the - in your regex for special characters. Updated regex:

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

Upvotes: 2

Alan Moore
Alan Moore

Reputation: 75252

[@-_.] matches a period (.) or any character in the range @ to _. That includes all the uppercase ASCII letters plus the square brackets, backslash, caret (^), and of course, @ and _. To match a literal hyphen, you either escape the hyphen with a backslash ([@\-_.]) or move it to the end of the list ([@_.-]).

Upvotes: 0

Related Questions