Textfield Validation using CharacterSet

1.5k Views Asked by At

I have written below code to validate text input in textfield.

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
    }

Can anyone help me to convert character(at:) and characterIsMember() part to its swift equivalent in the above code.

4

There are 4 best solutions below

2
vadian On BEST ANSWER

You can simplify the logic just by checking the range of the inverted character set. If the string contains only allowed characters the function 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
}
1
Gareth Miller On

You could work with something along these lines. I appreciate this is a bit rough and ready but should work:

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
    }
4
excitedmicrobe On

Use 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
 }
4
Sulthan On

Note that there is a simpler way to implement what you want using a regular expression:

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