Swift: Validate Username Input

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)
    }
}

func validateUsername(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
}

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
}

Tags:

Ios

Regex

Swift