Sujal
Sujal

Reputation: 1527

Regex for password of minimum 8 characters, including at least 3 of these: uppercase character, lowercase character, number and special character

Following is the regex that I am currently using for validating passwords: at least one uppercase character, at least one lowercase character, at least one number and minimum 8 characters in length.

func isValidPassword() -> Bool {
    let passwordRegEx = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$"
    return NSPredicate(format:"SELF MATCHES %@", passwordRegEx).evaluate(with: self)
}

I would now like to include special characters and update the validation rule as follows.

minimum 8 characters in length, should include at least 3 of these: uppercase character, lowercase character, number and special character.

What would be the regex for this requirement?

Upvotes: 0

Views: 1643

Answers (1)

Andreas Oetjen
Andreas Oetjen

Reputation: 10199

I think you better write a for-loop to iterate through the single characters and keep track of which createria has already passed, instead of creating a more and more complex regular expression.

  • The regex will be hard to understand / maintained by any programmer in just a few month. And any programmer includes you in a few months
  • You could provide detailled information to the user if the requiremens do not match. You could display a message "No uppercase character found in password" etc.
  • You could (more) easily implement stuff like "disallow repeating numbers" and so on
  • Although performance does not matter, regexp will be way slower than looping.

Upvotes: 2

Related Questions