0

I would like to be able to restrict the characters that can be entered into a textfield, for instance I want to restrict to only 1-5 numbers (1,2,3, and 5) and if the user enters a number greater than 5, I want the textField to do nothing.

I have seen how to restrict the length but I couldn't find anything for restricting certain character as I'm describing above.

I tried using the editingQtyFieldChanged but it doesn't quite do what I want.

myField.addTarget(self, action: #selector(UserInputViewController.fieldChanged), forControlEvents: UIControlEvents.EditingChanged)

func fieldChanged(){
    let number = Int(myField.text!)

    if number < 2{
        print("Number not allowed")
    }
}

Restrict to only numbers 1-5 in a uitextfield in Swift?

EDIT: Here is my solution, thanks to this thread.

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let numbers = ["6","7","8", "9"]
        for number in numbers{
            if string == number{
                return false
            }
        }
  }
Community
  • 1
  • 1
fs_tigre
  • 10,650
  • 13
  • 73
  • 146

2 Answers2

5

I do this as a string extension

extension String {

   var containsValidCharacter: Bool {
        let characterSet = CharacterSet(charactersIn: "12345")
        let range = (self as NSString).rangeOfCharacter(from: characterSet)
        return range.location != NSNotFound
    }
}

And then in your shouldChangeCharactersIn method.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    return !string.containsValidCharacter
}
Frankie
  • 11,508
  • 5
  • 53
  • 60
  • Thank you for your suggestion. – fs_tigre Oct 25 '16 at 00:40
  • Nice solution, only is there no reason to invert `!` before returning and does the `shouldChangeCharactersInRage` function also block a backspace. In order to fix this I had to insert `guard string != "" else { return true }` before `return string.containsValidCharacter` – RWIL Jan 30 '18 at 10:19
1

In the textFieldDidEndEditing delegate, parse the text and convert it to a number. If the number isn't within your range, then set the text to its previous value or take whatever action is appropriate.

pscuderi
  • 1,554
  • 12
  • 14