I am working on textfields validations and getting confused how to validate textfield must contain at least 1 character from all of the following categories: English uppercase characters (A - Z). English lowercase characters (a - z).
Asked
Active
Viewed 1,534 times
2
-
What's confusing? Where's your code? – AgRizzo May 28 '19 at 11:09
-
Check this https://stackoverflow.com/questions/15132276/password-validation-in-uitextfield-in-ios/15158351 might be helpful – Jignesh Kanani May 28 '19 at 11:09
4 Answers
2
Have a look at CharacterSet
s (described here)
You can create various Character sets (lowercase letters for instance) and test whether a string has content that matches said character set.
So, you could create a function which returns a boolean. The function checks your string against two CharacterSet
s and only if both can be found in the string, does the function return true
.
Something like this
func validate(string: String) -> Bool {
let lowercase = CharacterSet.lowercaseLetters
let uppercase = CharacterSet.uppercaseLetters
let lowercaseRange = string.rangeOfCharacter(from: lowercase)
let uppercaseRange = string.rangeOfCharacter(from: uppercase)
return lowercaseRange != nil && uppercaseRange != nil
}
validate(string: "Hello") //returns true
validate(string: "hello") //returns false
validate(string: "HELLO") //returns false
Have a look at this article from NSHipster to learn more.

pbodsk
- 6,787
- 3
- 21
- 51
1
Credit : TextField uppercase and lowercase validation
Here is the regext for the condition :- Minimum 8 characters, 1 uppercase and 1 number.
^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}
extension String {
func isValidPassword() -> Bool {
let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)
return passwordValidation.evaluate(with: self)
}
}
//Example 1
var password = "@Abcdef011" //string from UITextField (Password)
password.isValidPassword() // -> true
//Example 2
var password = "wer011" //string from UITextField
password.isValidPassword() // -> false

Taimoor Suleman
- 1,588
- 14
- 29
-
2credit where credit is due: https://stackoverflow.com/a/40526112/4063602 – pbodsk May 28 '19 at 11:31
0
func isValidPassword(testStr:String?) -> Bool {
guard testStr != nil else { return false }
// at least one uppercase,
// at least one lowercase
// 8 characters total
let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[a-z]).{8,}")
return passwordTest.evaluate(with: testStr)
}

Nimantha
- 6,405
- 6
- 28
- 69

Amit gupta
- 553
- 3
- 10
0
Simple extension accepts any CharacterSet
to check:
extension String {
func hasCharacter(in characterSet: CharacterSet) -> Bool {
return rangeOfCharacter(from: characterSet) != nil
}
}
usage:
"aBc".hasCharacter(in: .lowercaseLetters)
"aBc".hasCharacter(in: .uppercaseLetters)

Mojtaba Hosseini
- 95,414
- 31
- 268
- 278