Chris Chris - 4 years ago 381
Swift Question

Test UITextField text string to only contain alphanumeric characters

Im trying to complete form validation in Swift and cant find a way of testing for only Alphanumeric characters in a UITextField.text.

Ive found NSCharacterSet to help test if at least 1 letter has been entered (so far):

@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 a way to validate that only numbers, letters (maybe even underscores and dashes) to be entered. Loads of stuff out there for Obj-C but I need a SWIFT solution please.

Thank you in advance.

Answer Source

Check if the inversion of your accepted set is present:

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 chars, you will probably have to create a character set by your own. But the inversion logic will stay the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download