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.

Shashank
  • 13,713
  • 5
  • 37
  • 63
  • 1
    https://www.google.co.in/search?q=ypeError:+expected+a+character+buffer+object&ie=UTF-8&sa=Search&channel=fe&client=browser-ubuntu&hl=en&gws_rd=cr,ssl&ei=EOchVZS3JYLv8gXJkoHwCA#channel=fe&hl=en-IN&q=site:stackoverflow.com+regex+password+validation – Avinash Raj Apr 06 '15 at 04:20

1 Answers1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643