RubberDucky4444 RubberDucky4444 - 7 months ago 26
Swift Question

Swift live text field checking for characters from multiple arrays

I have a text field which will serve as a password input. I have created 4 arrays

upperCaseAll = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

lowerCaseAll = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

numberAll = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 0]

specialCharAll = ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\"", ".", ",", "?", "!", "'", "[", "]", "{", "}", "#", "%", "^", "\\", "|", "~", "<", ">", "€", "£", "¥", "•", ".", ","]


I am trying to make the user type at least one of each type of character.
I have 4 text views that will turn from red to green once each rule is met.
Then when all rules are met the red text views turn green and the login button is enabled

My question is how do I live check the text field to see if it has satisfied a rule? I imagine it would have to check each of the arrays overtime a character is entered

Oh also should the numbers be Ints or Strings?

Thanks

Answer

It's easier if you use Set instead of Array. Here's an example:

private let upperCaseAll = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
private let lowerCaseAll = Set("abcdefghijklmnopqrstuvwxyz".characters)
private let numberAll = Set("0123456789".characters)
private let specialCharAll = Set("-/:;()$&@\".,?!'[]{}#%^\\|~<>€£¥".characters)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Determines what the new value of the text field will be
    let newText = range.length == 0 ? textField.text! + string : (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    // Turn that string into a Set of Characters
    let characters = Set(newText.characters)

    let hasUpperCase = !characters.intersect(self.upperCaseAll).isEmpty
    let hasLowerCase = !characters.intersect(self.lowerCaseAll).isEmpty
    let hasNumber = !characters.intersect(self.numberAll).isEmpty
    let hasSpecialChar = !characters.intersect(self.specialCharAll).isEmpty

    // Now turn your 4 other views to green/red as needed
    print("hasUpperCase = \(hasUpperCase), hasLowercase = \(hasLowerCase), hasNumber = \(hasNumber), hasSpecialChar = \(hasSpecialChar)")
    ...

    return true
}
Comments