使用CharacterSet进行文本字段验证

时间:2019-03-01 11:08:43

标签: ios swift nscharacterset

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

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等价物。

4 个答案:

答案 0 :(得分:4)

您只需检查倒置字符集的范围即可简化逻辑。如果字符串仅包含允许的字符,则该函数返回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
}

答案 1 :(得分:1)

请注意,有一种使用正则表达式实现所需内容的简单方法:

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

答案 2 :(得分:0)

您可以按照以下方式使用某些东西。我赞赏这有点粗糙且可以使用,但应该可以:

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
    }

答案 3 :(得分:0)

使用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
 }