如何设置 uitextfield 以便用户键入的内容必须满足特定条件(即大写、数字等)?

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

我正在尝试设置用户必须创建的特定条件才能创建新帐户。评判标准如下:

  1. 密码必须以字母开头
  2. 至少1个大写字母
  3. 至少1个小写字母
  4. 至少 1 个号码
  5. 至少 1 个特殊字符
  6. 密码不能包含用户名

有更多标准,但这些是给我带来最多问题的标准。非常感谢对其中任何一个的任何帮助!

创建循环遍历输入密码的每个字符并检查它是否包含在特定字符串中的函数。对于大写字母, 遍历密码的每个字符,如下所示:

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.

试试这个方法:

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
}