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.
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
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With