我需要在我的快速代码中限制用户名的字符。
Username
只能使用那些字符"abcdefghijklmnopqrstuvwxyz._1234567890"
。
如果我不是菜鸟,请原谅我,我没有编程背景。还在学习。
下面是快速代码,我需要编辑哪一部分?
// MARK: - SIGNUP BUTTON
@IBAction func signupButt(_ sender: AnyObject) {
dismissKeyboard()
// You acepted the TOS
if tosAccepted {
if usernameTxt.text == "" || passwordTxt.text == "" || emailTxt.text == "" || fullnameTxt.text == "" {
simpleAlert("You must fill all fields to sign up on \(APP_NAME)")
self.hideHUD()
} else {
showHUD("Please wait...")
let userForSignUp = PFUser()
userForSignUp.username = usernameTxt.text!.lowercased()
userForSignUp.password = passwordTxt.text
userForSignUp.email = emailTxt.text
userForSignUp[USER_FULLNAME] = fullnameTxt.text
userForSignUp[USER_IS_REPORTED] = false
let hasBlocked = [String]()
userForSignUp[USER_HAS_BLOCKED] = hasBlocked
// Save Avatar
let imageData = avatarImg.image!.jpegData(compressionQuality: 1.0)
let imageFile = PFFile(name:"avatar.jpg", data:imageData!)
userForSignUp[USER_AVATAR] = imageFile
userForSignUp.signUpInBackground { (succeeded, error) -> Void in
if error == nil {
self.hideHUD()
let alert = UIAlertController(title: APP_NAME,
message: "We have sent you an email that contains a link - you must click this link to verify your email and go back here to login.",
preferredStyle: .alert)
// Logout and Go back to Login screen
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
PFUser.logOutInBackground(block: { (error) in
self.dismiss(animated: false, completion: nil)
})
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
// ERROR
} else {
self.simpleAlert("\(error!.localizedDescription)")
self.hideHUD()
}}
}
答案 0 :(得分:3)
您可以为此使用正则表达式,请查看下面的代码。
let usernameRegex = "^[a-zA-Z0-9]{4,10}$"
let usernameTest = NSPredicate(format:"SELF MATCHES %@", usernameRegex)
print(usernameTest.evaluate(with: "asAZ")) // boolen
您甚至可以像这样用它来创建extension
extension String {
func isValidUserName() -> Bool{
let usernameRegex = "^[a-zA-Z0-9]{4,10}$" // your regex
let usernameTest = NSPredicate(format:"SELF MATCHES %@", usernameRegex)
return usernameTest.evaluate(with: self)
}
}
像这样使用它
yourText.isValidUserName() // return true or false .
您可以使用谷歌搜索任何形式的正则表达式以适应您的情况,甚至将来使用,我什至建议您将那些正则表达式保存在枚举中,并创建一个接受这些枚举并进行验证的函数,将其视为提示
enum ValidationRgex: String {
case username = "^[a-zA-Z0-9]{4,10}$"
}
extension String {
func isValid(_ regex: ValidationRgex) -> Bool{
let usernameRegex = regex.rawValue
let usernameTest = NSPredicate(format:"SELF MATCHES %@", usernameRegex)
return usernameTest.evaluate(with: self)
}
}
"MyText".isValid(.username) // usage