Swift:验证用户名输入 [英] Swift: Validate Username Input

查看:110
本文介绍了Swift:验证用户名输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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:



  • 没有特殊字符(例如@,#,$, %,&,*,(,),^,<,>,!,±)

  • 只允许使用字母,下划线和数字

  • 长度最多18个字符,最少7个字符

我在哪里可以找到验证的函数输入字符串(函数参数)并根据以上条件返回true或false?我对正则表达式不是很精通。

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.

推荐答案

你可以使用

^\w{7,18}$

\A\w{7,18}\z

请参阅正则表达式演示

模式详情


  • ^ - 字符串的开头(可以用 \A 替换,以确保只启动字符串匹配)

  • \ w {7,18} - 7到18个字符(即任何 Unicode 字母,数字或下划线,如果您只允许使用ASCII字母和数字,请使用 [a-zA-Z0-9] [a-zA-Z0-9_ ] 代替)

  • $ - 字符串结束(用于验证,我宁愿使用 \ z 改为确保字符串结尾只匹配)。

  • ^ - 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).

SWI ft代码

请注意,如果您使用 NSPredicate MATCHES ,你不需要字符串锚的开始/结束,因为匹配将默认锚定:

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
}

这篇关于Swift:验证用户名输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆