Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created May 2, 2014 16:47
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pmarreck/4c5f1076498da1a86062 to your computer and use it in GitHub Desktop.
Save pmarreck/4c5f1076498da1a86062 to your computer and use it in GitHub Desktop.
Example of using regex to check a complex password validation requirement ("use at least 1 character from 3 sets of characters out of a total of 4 sets of characters")
PASSWORD_VALIDATOR = /( # Start of group
(?: # Start of nonmatching group, 4 possible solutions
(?=.*[a-z]) # Must contain one lowercase character
(?=.*[A-Z]) # Must contain one uppercase character
(?=.*\W) # Must contain one non-word character or symbol
| # or...
(?=.*\d) # Must contain one digit from 0-9
(?=.*[A-Z]) # Must contain one uppercase character
(?=.*\W) # Must contain one non-word character or symbol
| # or...
(?=.*\d) # Must contain one digit from 0-9
(?=.*[a-z]) # Must contain one lowercase character
(?=.*\W) # Must contain one non-word character or symbol
| # or...
(?=.*\d) # Must contain one digit from 0-9
(?=.*[a-z]) # Must contain one lowercase character
(?=.*[A-Z]) # Must contain one uppercase character
) # End of nonmatching group with possible solutions
.* # Match anything with previous condition checking
)/x # End of group
@pmarreck
Copy link
Author

pmarreck commented May 2, 2014

Note: I did not add a length requirement to the regex because the Rails ActiveRecord validation call itself had it, which ensured that Rails would treat any length requirement validation failures with a separately descriptive error message:

validates :password, {confirmation: true, presence: true, length: { minimum: 8 }, format: {
        with: PASSWORD_VALIDATOR,
        message: "must contain 3 of the following 4: a lowercase letter, an uppercase letter, a digit, a non-word character or symbol"
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment