UITextField test text string contains only alphanumeric characters

Im trying to complete form validation in Swift and cannot find a way to test only alphanumeric characters in UITextField.text.

Ive discovered that NSCharacterSet helps to check if at least 1 letter has been entered (for now):

@IBOutlet weak var username: UITextField! let letters = NSCharacterSet.letterCharacterSet() //Check username contains a letter if (username.text!.rangeOfCharacterFromSet(letters) == nil) { getAlert("Error", message: "Username must contain at least 1 letter") } 

Now I just need to check that I need to enter only numbers, letters (maybe even underscores and dashes). Download material for Obj-C, but I need a SWIFT solution, please.

Thanks in advance.

+5
source share
2 answers

Check if there is an inverse of your accepted set:

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

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

If you want to accept underscores or more characters, you may have to create a character set of your choice. But the logic of inversion will remain the same.

+6
source

Although it’s too late to answer, this answer may be useful to someone.

It is simple and works like a charm to me.

Swift 3:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic /// 2. replacementString is empty means we are deleting text: return true if string.characters.count > 0 { var allowedCharacters = CharacterSet.alphanumerics /// add characters which we need to be allowed allowedCharacters.insert(charactersIn: " -") // "white space & hyphen" let unwantedStr = string.trimmingCharacters(in: allowedCharacters) return unwantedStr.characters.count == 0 } return true } 

Note. This will work for inserting lines into a text field. The inserted line will not be displayed in the text box if it contains any unwanted characters.

+1
source

Source: https://habr.com/ru/post/1239672/


All Articles