Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Validate Username Input

Tags:

regex

ios

swift

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.

like image 531
ksa_coder Avatar asked Jun 21 '16 07:06

ksa_coder


2 Answers

You may use

^\w{7,18}$

or

\A\w{7,18}\z

See the regex demo

Pattern details:

  • ^ - 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. any Unicode letters, digits or underscores, if you only allow ASCII letters and digits, use [a-zA-Z0-9] or [a-zA-Z0-9_] instead)
  • $ - end of string (for validation, I'd rather use \z instead to ensure end of string only matches).

Swift code

Note that if you use it with NSPredicate and MATCHES, you do not need the start/end of string anchors, as the match will be anchored by default:

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

Else, you should not omit the anchors:

func isValidInput(Input:String) -> Bool {
    return Input.range(of: "\\A\\w{7,18}\\z", options: .regularExpression) != nil
}
like image 136
Wiktor Stribiżew Avatar answered Nov 04 '22 14:11

Wiktor Stribiżew


In Swift 4

extension String {

    var isValidName: Bool {
       let RegEx = "^\\w{7,18}$"
       let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
       return Test.evaluate(with: self)
    }
}
like image 39
Sourabh Kumbhar Avatar answered Nov 04 '22 16:11

Sourabh Kumbhar