Edson Francis
Edson Francis

Reputation: 19

How to limit character for username in Swift

i need to limit character for username in my swift code.

Username only can use those characters "abcdefghijklmnopqrstuvwxyz._1234567890".

Please forgive me if i'm noob, i don't have programming background. Still learning .

Below are swift code, which part i need to edit ?

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

Upvotes: 0

Views: 198

Answers (1)

Mohmmad S
Mohmmad S

Reputation: 5088

You can use regex for this, check out the code below.

let usernameRegex = "^[a-zA-Z0-9]{4,10}$"
let usernameTest = NSPredicate(format:"SELF MATCHES %@", usernameRegex)
print(usernameTest.evaluate(with: "asAZ")) // boolen

You can even create an extension out of it like this

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

}

use it like this

yourText.isValidUserName() // return true or false . 

You can google any kind of regex to fit your case, and future ones, i even recommend saving those regex in an enum, and create a function that accept those enums and validate, look at this as a hint

  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 

Upvotes: 3

Related Questions