Adrian Adrian - 4 months ago 24
iOS Question

Accounting for backspace in UITextField validation using shouldChangeCharactersInRange

I'm attempting to put validation in a textField to ensure it only contains letters. It works until I press backspace.

As a workaround, I tried to create a

NSMutableCharacterSet
and use
formUnionWithCharacterSet
to add
NSCharacterSet.letterCharacterSet()
. Then I added backspace to it. That's not working either.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Limit to Letters & Backspace
// let charactersAllowed = NSCharacterSet.letterCharacterSet()
let charactersAllowed = NSMutableCharacterSet()
charactersAllowed.formUnionWithCharacterSet(NSCharacterSet.letterCharacterSet())
charactersAllowed.addCharactersInString("\\b")

if let rangeOfCharactersAllowed = string.rangeOfCharacterFromSet(charactersAllowed, options: .CaseInsensitiveSearch) {
return rangeOfCharactersAllowed.count == string.characters.count
} else {
displayAlert("Invalid Character", alertMessage: "Please enter only letters")
return false
}
}


I've found some old crusty answers in Objective-C, but none of them seem to work for me. Any other suggestions for going to
NSMutableCharacterSet
route for validation?

If it helps, I'm using the simulator and attempting to press the backspace key (delete) in the upper-right-hand corner of the keyboard.

Answer

Try this:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
  let notLetterSet = NSCharacterSet.letterCharacterSet().invertedSet
  let textFieldInvalidCharPosition = string.rangeOfCharacterFromSet(notLetterSet)

if (textFieldInvalidCharPosition != nil) {
     return false
  } else {
     return true
  }
}
Comments