SwiftyJD SwiftyJD - 1 month ago 12
iOS Question

How to set up uitextfield so what the user types has to meet specific criteria(ie. uppercase, number, etc.)?

I'm trying to set up specific criteria the user must create in order to create a new account. The criteria is as follows:


  1. Password must start with a letter

  2. At least 1 upper case letter

  3. At least 1 lower case letter

  4. At least 1 number

  5. At least 1 Special Character

  6. The password may not contain username



There was more criteria but these are the ones giving me the most problems. Any help on any of them is greatly appreciated!

Answer

Try this method:

func validate(pass: String, userName: String) -> Bool {
    guard pass.characters.count > 0 else {return false }
    guard pass != userName else {return false }

    //Checks if the first character is a lowercase letter
    let firstIndex = pass.index(pass.startIndex, offsetBy: 1)
    guard pass.substring(to: firstIndex).rangeOfCharacter(from: CharacterSet.lowercaseLetters) != nil else { return false }

    guard pass.rangeOfCharacter(from: CharacterSet.uppercaseLetters) != nil else { return false }
    guard pass.rangeOfCharacter(from: CharacterSet.lowercaseLetters) != nil else { return false }
    guard pass.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil else { return false }

    let characterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
    guard pass.rangeOfCharacter(from: characterSet.inverted) != nil else { return false }

    return true
}