Check if a String is alphanumeric in Swift
extension String {
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}
"".isAlphanumeric // false
"abc".isAlphanumeric // true
"123".isAlphanumeric // true
"ABC123".isAlphanumeric // true
"iOS 9".isAlphanumeric // false
I felt the accepted answer using regex was concrete but a rather heavy solution. You could check it this way also in Swift 3.0:
if yourString.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
return "Username can only contain numbers or digits"
}
A modern Swift 3 and 4 solution
extension String {
func isAlphanumeric() -> Bool {
return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
}
func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
if ignoreDiacritics {
return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != ""
}
else {
return self.isAlphanumeric()
}
}
}
Usage:
"".isAlphanumeric() == false
"Hello".isAlphanumeric() == true
"Hello 2".isAlphanumeric() == false
"Hello3".isAlphanumeric() == true
"Français".isAlphanumeric() == true
"Français".isAlphanumeric(ignoreDiacritics: true) == false
This works with languages other than English, allowing diacritic characters like è and á, etc. If you'd like to ignore these, use the flag "ignoreDiacritics: true
".