Check password string strength criteria in Swift
update: Xcode 8.3.2 • Swift 3.1
enum PasswordError: String, Error {
case eightCharacters
case oneUppercase
case oneLowercase
case oneDecimalDigit
}
extension String {
func validatePassword() throws {
guard count > 7
else { throw PasswordError.eightCharacters }
guard rangeOfCharacter(from: .uppercaseLetters) != nil
else { throw PasswordError.oneUppercase }
guard rangeOfCharacter(from: .lowercaseLetters) != nil
else { throw PasswordError.oneLowercase }
guard rangeOfCharacter(from: .decimalDigits) != nil
else { throw PasswordError.oneDecimalDigit }
}
}
let myPass = "12345678"
do {
try myPass.validatePassword()
print("valid password action")
} catch let error as PasswordError {
print("Password error:", error)
switch error {
case .eightCharacters:
print("Needs At Least Eight Characters action")
case .oneUppercase:
print("Needs At Least one Uppercase action")
case .oneLowercase:
print("Needs At Least one Lowercase action")
case .oneDecimalDigit:
print("Needs At Least One DecimalDigit action")
}
} catch {
print("error:", error)
}
Try this:
^(?=.*\d)(?=.*[a-zA-Z]).{8,}$
or
^(?=.*\d)(?=.*[a-zA-Z])(?!.*[\W_\x7B-\xFF]).{8,}$
The first does not care about special characters, the second disallows them.