String validation in Swift

Vik Denic
vik’s code journal
1 min readDec 8, 2015

When building an app with user accounts, one often needs to restrict usernames to only contain certain characters (i.e. alphanumerics and underscores).

I’ve written an extension on the String class to validate whether or not a String only contains these permitted characters:

Here’s the Gist so you can easily copy-and-paste it if needed: https://gist.github.com/vikdenic/eb7bab00295649c081c1

Basically, we create a character set of all the characters we will allow. And then invert this set. From this inverted set, we can now check if our string has any characters that we will not allow. And return our Bool accordingly.

--

--