ksa_coder ksa_coder - 5 months ago 111
Swift Question

Swift: Validate Username Input

Working on a Swift app and I have a form filled by user and I would like the user to select their own username. The only constraints I want on the username are:



  • No special characters (e.g. @,#,$,%,&,*,(,),^,<,>,!,±)

  • Only letters, underscores and numbers allowed

  • Length should be 18 characters max and 7 characters minimum




Where can I find a function that validates an input string (function parameter) and return true or false based on above criteria? I am not very well versed in regular expressions.

Answer

Use NSPredicate with MATCHES and the following regex:

^\w{7,18}$

See the regex demo

The pattern matches:

  • ^ - start of the string (can be replaced with \A to ensure start of string only matches)
  • \w{7,18} - 7 to 18 word characters (i.e. letters, digits or underscores)
  • $ - end of string (for validation, I'd rather use \z instead to ensure end of string only matches).

Swift code:

func isValidInput(Input:String) -> Bool {
    let RegEx = "\\A\\w{7,18}\\z"
    let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
    return Test.evaluateWithObject(Input)
}
Comments