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!
Asked
Active
Viewed 156 times
-1
-
1Have 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 Answers
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
}