-3

I am working on an iOS app where I require users to input their username without special characters.

I need assistance creating a function to validate a text field to accept only letters, numbers, and underscore. And when implement it into the signup Button action, I want to call the function and add an if case for the validation.

Can someone tell me what to do? I have tried other methods online but they seem to be outdated and nothing worked for me.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
KingJulian
  • 45
  • 1
  • 9
  • https://stackoverflow.com/questions/38933193/swift-ios-alpha-numeric-regex-that-allows-underscores-and-dashes – Arun Jul 10 '17 at 07:32
  • 4
    *"I have tried other methods online"* what did you try? – *"but they seem to be outdated"* why? Examples? – *"nothing worked for me"* is a useless description. How did it "not work"? – Martin R Jul 10 '17 at 07:32
  • Create NSCharacterSet containing alphanumerics and an underscore, like that: https://stackoverflow.com/questions/2767675/nscharacterset-how-do-i-add-to-alphanumericcharacterset-text-restriction Then, for each character call `myCharacterSet.characterIsMember(myChar)` – mag_zbc Jul 10 '17 at 07:32

3 Answers3

0

You can use regex to solve this.

You just want a string full of letters, number and underscores and nothing else, so this regex will suffice:

^[\w]+$

You can write in code like this:

let regex = try! NSRegularExpression(pattern: "^[\\w]+$", options: [])
if regex.firstMatch(in: yourTextField.text!, options: [], range: NSRange(location: 0, length: yourTextField.text!.characters.count)) != nil {
    // the string is valid
 }
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0
func checkUsername(str: String) -> Bool
{
    do
{
    let regex = try NSRegularExpression(pattern: "^[0-9a-zA-Z\\_]{7,18}$", options: .CaseInsensitive)
    if regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count)).count > 0 {return true}
    }
catch {}
return false
}
0

In Swift 3.0, try this

function validation(strValue : String)-> Bool{

let aSet = NSCharacterSet(charactersIn:"^[0-9a-zA-Z\\_]{7,18}$").inverted
    let compSepByCharInSet = string.components(separatedBy: aSet)
    let numberFiltered = compSepByCharInSet.joined(separator: "")
    return string == numberFiltered

}
Berlin
  • 2,115
  • 2
  • 16
  • 28