H. Lamb H. Lamb - 4 months ago 37x
Swift Question

check if string contains anything outside of the character set swift

Hi I want to check if the user types in a string that contains anything outside of the character set (contains characters that are not specified in my set):


How can I achieve this? thanks in advance!


I tried using

var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location == NSNotFound){
println("No special characters")


but i'm getting a type 'range?' has no member 'location' error


Here is a simple solution, Just use NSCharacterSet like this :-

let name1="myname" // Input
let characterSet:  NSMutableCharacterSet = NSMutableCharacterSet.alphanumericCharacterSet()
name1.stringByTrimmingCharactersInSet(characterSet).isEmpty // If this return true, you enetered the right charcters