使用 CharacterSet 的文本域验证

Textfield Validation using CharacterSet

我编写了以下代码来验证文本字段中的文本输入。

else if (textField == txtField_Password)
    {
        let charSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$&*!")
        let charLength = (txtField_Password.text!.count) + (string.count) - range.length

        for i in 0..<string.count
        {
            let c = (string as NSString).character(at: i)
            if (!((charSet as NSCharacterSet).characterIsMember(c)))
            {
                return false
            }
        }
        return (charLength > 20) ? false : true
    }

任何人都可以帮助我将 character(at:) 和 characterIsMember() 部分转换为上面代码中的 swift 等价物。

您可以按照这些思路进行操作。我很欣赏这有点粗糙,但应该可以工作:

charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$&*!"

if txtField_Password.text!.count <= 20 {

    for i in 0..<str.count
    {
        let c = Array(str)[i]

        let cString = String(c)

        if charSet.contains(cString) {
            return false
           }
        }

    } else {
        return false
    }

使用rangeOfCharacter:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
       let specialCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$&*!"


       let characterSet = CharacterSet(charactersIn: specialCharacters)

       guard let lengh = textfield.text else {return} 
       if lengh.count >= 20 {
         // text exceeded 20 characters. Do something 
       }     

       if (string.rangeOfCharacter(from: characterSet) != nil) {
              print("matched")
              return true
          } else { 
              print("not matched")
       }

    return true
 }

您可以通过检查 inverted 字符集的范围来简化逻辑。如果字符串仅包含允许的字符,则函数 returns nil.

else if textField == txtField_Password {
    let charLength = txtField_Password.text!.utf8.count + string.utf8.count - range.length
    let charSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$&*!")
    return string.rangeOfCharacter(from: charSet.inverted) == nil && charLength < 21
}

请注意,有一种更简单的方法可以使用正则表达式来实现您想要的功能:

let currentText = (textField.text ?? "") as NSString
let newText = currentText.replacingCharacters(in: range, with: string)

let pattern = "^[a-zA-Z0-9@$&*!]{0,20}$"
return newText.range(of: pattern, options: .regularExpression) != nil