-1

In my project user's can type out the username they want. I will like to restrict this field where they can only use letters, numbers and a underscore (like Instagram). I've searched the internet for hours but can not come up with anything. How can I do this? Thank you in advance!

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
ap123
  • 916
  • 1
  • 8
  • 22
  • 1
    Have a look at [this](https://stackoverflow.com/questions/37938435/swift-validate-username-input) question which fully describes it :) – George Apr 17 '18 at 21:50

1 Answers1

2
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
      guard !s.isEmpty else { return true }
      let numberFormatter = NumberFormatter()
      numberFormatter.numberStyle = .none
      return numberFormatter.number(from: s)?.intValue != nil
 }