0

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!

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

2 Answers2

2

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
}
alexburtnik
  • 7,661
  • 4
  • 32
  • 70
-1

Create functions that loop through each character of the entered password and check to see if it is contained in a particular string. For the upper case letter, loop through each character of the password, like this:

for c in password.characters {
    if "ABCDEFGHIJKLMNOPQRSTUVWXYZ".range(of:String(c)) != nil {
        return
    }
}
//if for loop is exited, alert user that their password is invalid.
Adam Zarn
  • 1,868
  • 1
  • 16
  • 42
  • I just tried this, I get an error " Cannot convert value of type 'String.CharacterView._Element' (aka 'Character') to expected argument type 'String'" – SwiftyJD Oct 17 '16 at 20:24
  • Sorry, try converting c to a string like this: String(c) – Adam Zarn Oct 17 '16 at 20:28