2

Disclaimer: This is a Codewars problem.

You need to write regex that will validate a password to make sure it meets the following criteria:

  • At least six characters long
  • contains a lowercase letter
  • contains an uppercase letter
  • contains a number

Valid passwords will only be alphanumeric characters.

So far, this is my attempt:

function validate(password) {
    return /^[A-Za-z0-9]{6,}$/.test(password);
}

What this does so far is make sure that each character is alphanumeric and that the password has at least 6 characters. It seems to work properly in those regards.

I am stuck on the part where it requires that a valid password have at least one lowercase letter, one uppercase letter, and one number. How can I express these requirements along with the previous ones using a single regular expression?

I could easily do this in JavaScript, but I wish to do it through a regular expression alone since this is what the problem is testing.

1

1 Answer 1

21

You need to use lookaheads:

function validate(password) {
    return /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])[A-Za-z0-9]{6,}$/.test(password);
}

Explanation:

^               # start of input 
(?=.*?[A-Z])    # Lookahead to make sure there is at least one upper case letter
(?=.*?[a-z])    # Lookahead to make sure there is at least one lower case letter
(?=.*?[0-9])    # Lookahead to make sure there is at least one number
[A-Za-z0-9]{6,} # Make sure there are at least 6 characters of [A-Za-z0-9]
$               # end of input
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.