Search code examples
iosswiftnscharacterset

Textfield Validation using CharacterSet


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.


Solution

  • 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
    }