Reputation: 67
I am trying to validate a password with the following rules:
So far I wrote this code:
[0-9a-zA-Z] (?=(.*\d){2}) {8,}
Im not sure why the passwords I enter returns invalid although it follows the rules.
Upvotes: 0
Views: 66
Reputation: 626926
Remember that spaces are meaningful in a regex pattern, so you require at least 8 spaces at the end. There are no anchors in the regex, so the length limitation might not work even if you write a correct pattern. So far, this will match an alphanumeric, a space that is followed with 2 occurrences of any 0+ chars followed with a digit, but since there is space with {8,}
quantifier, this pattern will never match anything.
You need
^(?=.{8})[a-zA-Z]*(?:\d[a-zA-Z]*){2}[a-zA-Z0-9]*$
See the regex demo
^
- start of string(?=.{8})
- at least 8 chars[a-zA-Z]*
- zero or more letters(?:\d[a-zA-Z]*){2}
- 2 sequences of:
\d
- a digit (may be replaced with [0-9]
)[a-zA-Z]*
- zero or more letters[a-zA-Z0-9]*
- 0+ alphanumeric chars$
- end of string.Alternatively, you may use
^(?=(?:[a-zA-Z]*\d){2})[a-zA-Z0-9]{8,}$
Here, (?=(?:[a-zA-Z]*\d){2})
will require at least 2 occurrences of 0+ letters followed with a digit in the string and [a-zA-Z0-9]{8,}
will match 8 or more alphanumeric chars.
Upvotes: 1