H. Lamb H. Lamb - 6 months ago 61
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):

"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-."

How can I achieve this? thanks in advance!

update

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

Answer

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

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