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.
Alphanumeric is a description of data that is both letters and numbers. For example, "1a2b3c" is a short string of alphanumeric characters. Alphanumeric is commonly used to help explain the availability of text that can be entered or used in a field, such as an alphanumeric password field.
An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Explanation: This string contains all the alphabets from a-z, A-Z, and the number from 0-9. Therefore, it is an alphanumeric string.
Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.
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.
Though it's late to answer, but this answer might be useful to someone.
This is simple and worked like a charm for 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 pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With