Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for password

I'm trying to get regex for minimum requirements of a password to be minimum of 6 characters; 1 uppercase, 1 lowercase, and 1 number. Seems easy enough? I have not had any experience in regex's that "look ahead", so I would just do:

if(!pwStr.match(/[A-Z]+/) || !pwStr.match(/[a-z]+/) || !pwStr.match(/[0-9]+/) ||
    pwStr.length < 6)
    //was not successful

But I'd like to optimize this to one regex and level up my regex skillz in the process.

like image 450
Nick Rolando Avatar asked Feb 20 '26 22:02

Nick Rolando


2 Answers

^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!&$%&? "]).*$
  • ^.*
    Start of Regex
  • (?=.{6,})
    Passwords will contain at least 6 characters in length
  • (?=.*[a-zA-Z])
    Passwords will contain at least 1 upper and 1 lower case letter
  • (?=.*\d)
    Passwords will contain at least 1 number
  • (?=.*[!#$%&? "]) Passwords will contain at least given special characters
  • .*$
    End of Regex

here is the website that you can check this regex - http://rubular.com/

like image 92
AMIC MING Avatar answered Feb 22 '26 10:02

AMIC MING


Assuming that a password may consist of any characters, have a minimum length of at least six characters and must contain at least one upper case letter and one lower case letter and one decimal digit, here's the one I'd recommend: (commented version using python syntax)

re_pwd_valid = re.compile("""
    # Validate password 6 char min with one upper, lower and number.
    ^                 # Anchor to start of string.
    (?=[^A-Z]*[A-Z])  # Assert at least one upper case letter.
    (?=[^a-z]*[a-z])  # Assert at least one lower case letter.
    (?=[^0-9]*[0-9])  # Assert at least one decimal digit.
    .{6,}             # Match password with at least 6 chars
    $                 # Anchor to end of string.
    """, re.VERBOSE)

Here it is in JavaScript:

re_pwd_valid = /^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^0-9]*[0-9]).{6,}$/;

Additional: If you ever need to require more than one of the required chars, take a look at my answer to a similar password validation question

Edit: Changed the lazy dot star to greedy char classes. Thanks Erik Reppen - nice optimization!

like image 29
ridgerunner Avatar answered Feb 22 '26 10:02

ridgerunner