Check if a string contains at least a upperCase letter, a digit, or a special character in Swift?
Simply replace your RegEx rule [A-Z]+ with .*[A-Z]+.* (and other RegEx rules as well)
Rules
[A-Z]+ matches only strings with all characters capitalized
Examples: AVATAR, AVA, TAR, AAAAAA
Won't work: AVATAr
.* matches all strings (0+ characters)
Examples: 1, 2, AVATAR, AVA, TAR, a, b, c
.*[A-Z]+.* matches all strings with at least one capital letter
Examples: Avatar, avataR, aVatar
Explanation:
I. .* will try to match 0 or more of anything
II. [A-Z]+ will require at least one capital letter (because of the +)
III. .* will try to match 0 or more of anything
Avatar [empty | "A" | "vatar"]
aVatar ["a" | "V" | "atar"]
aVAtar ["a" | "VA" | "tar"]
Working Code
func checkTextSufficientComplexity(var text : String) -> Bool{ let capitalLetterRegEx = ".*[A-Z]+.*" var texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx) var capitalresult = texttest!.evaluateWithObject(text) println("\(capitalresult)") let numberRegEx = ".*[0-9]+.*" var texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx) var numberresult = texttest1!.evaluateWithObject(text) println("\(numberresult)") let specialCharacterRegEx = ".*[!&^%$#@()/]+.*" var texttest2 = NSPredicate(format:"SELF MATCHES %@", specialCharacterRegEx) var specialresult = texttest2!.evaluateWithObject(text) println("\(specialresult)") return capitalresult || numberresult || specialresult}
Examples:
checkTextSufficientComplexity("Avatar") // true || false || falsecheckTextSufficientComplexity("avatar") // false || false || falsecheckTextSufficientComplexity("avatar1") // false || true || falsecheckTextSufficientComplexity("avatar!") // false || false || true
Here is a concise version of Joshuas answer in Swift 3, assuming that all validations must be fulfilled.
func validate(password: String) -> Bool { let capitalLetterRegEx = ".*[A-Z]+.*" let texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx) guard texttest.evaluate(with: password) else { return false } let numberRegEx = ".*[0-9]+.*" let texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx) guard texttest1.evaluate(with: password) else { return false } let specialCharacterRegEx = ".*[!&^%$#@()/_*+-]+.*" let texttest2 = NSPredicate(format:"SELF MATCHES %@", specialCharacterRegEx) guard texttest2.evaluate(with: password) else { return false } return true}
Another alternate solution.
You can do all the check using one regular expression.
RegExp: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}
You can use this as mention below:
//Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:let regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"let isMatched = NSPredicate(format:"SELF MATCHES %@", regex).evaluate(with: yourTextField.text)if(isMatched == true) { // Do your stuff ..} else { // Show Error Message.}