smartcoderx
smartcoderx

Reputation: 1081

Remove all non a-zA-Z and non number strings form textfield

The user should be enter only a-z, A-Z and 0-9. I show the user the UIKeyboardType.ASCIICapable keyboard layout.

How can i filter non a-z, A-Z and 0-9 from string after the user enter a string with keyboard.

How can i solve this issue? I'm using xcode 7 and swift 2.

Upvotes: 1

Views: 224

Answers (2)

Kumar KL
Kumar KL

Reputation: 15335

You need to work with delegate method of UITextField

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let set: NSCharacterSet = NSCharacterSet.alphanumericCharacterSet().invertedSet

       if string.rangeOfCharacterFromSet(set) != nil {
        return false
        }
        return true
    }

Upvotes: 1

Ashish Thakkar
Ashish Thakkar

Reputation: 944

Check if the inversion of your accepted set is present:

if yourtextfield.text!.rangeOfCharacterFromSet(letters.invertedSet) != nil {
    print("invalid")
}

letters should probably be alphanumericCharacterSet() if you want to include numbers as well.

Upvotes: 0

Related Questions