Created
July 18, 2016 14:05
-
-
Save Jxrgxn/26e247a0cf58f905f0d516b72283984c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct RegExp { | |
/** | |
Check password complexity | |
- parameter password: password to test | |
- parameter length: password min length | |
- parameter patternsToEscape: patterns that password must not contains | |
- parameter caseSensitivty: specify if password must conforms case sensitivity or not | |
- parameter numericDigits: specify if password must conforms contains numeric digits or not | |
- returns: boolean that describes if password is valid or not | |
*/ | |
static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool { | |
if (password.length < length) { | |
return false | |
} | |
if caseSensitivty { | |
let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0 | |
if !hasUpperCase { | |
return false | |
} | |
let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0 | |
if !hasLowerCase { | |
return false | |
} | |
} | |
if numericDigits { | |
let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0 | |
if !hasNumbers { | |
return false | |
} | |
} | |
if patternsToEscape.count > 0 { | |
let passwordLowerCase = password.lowercaseString | |
for pattern in patternsToEscape { | |
let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0 | |
if hasMatchesWithPattern { | |
return false | |
} | |
} | |
} | |
return true | |
} | |
static func matchesForRegexInText(regex: String, text: String) -> [String] { | |
do { | |
let regex = try NSRegularExpression(pattern: regex, options: []) | |
let nsString = text as NSString | |
let results = regex.matchesInString(text, | |
options: [], range: NSMakeRange(0, nsString.length)) | |
return results.map { nsString.substringWithRange($0.range)} | |
} catch let error as NSError { | |
print("invalid regex: \(error.localizedDescription)") | |
return [] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment