0

I am trying to validate a password with the following rules:

  • Must have at least eight characters.
  • Must contain ONLY letters and digits.
  • Must contain at least two digits.

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.

2
  • 1
    ...do you have a question? Commented Dec 9, 2016 at 7:53
  • Disallowing all non alphanumeric chars seems like a bad idea to me. Commented Dec 9, 2016 at 7:54

1 Answer 1

1

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,}$

See another regex demo

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.