Roduck Nickes Roduck Nickes - 7 months ago 17
Swift Question

Register form in application

So I have register form in my application, but a problem. Here is my code:

@IBAction func registerButtonAction(sender: AnyObject) {
if (fullnameTextField.text == ""){
self.fullnameTextField.shake()
}
if (usernameTextfield.text == ""){
self.usernameTextfield.shake()
}
if (usernameTextfield.text?.characters.count < 6){
usernameTextfield.shake()
}
if (emailTextfield.text == ""){
self.emailTextfield.shake()
}
if (passwordTextfield.text == ""){
self.passwordTextfield.shake()
}
if (retypepasswordTextfield.text == ""){
self.retypepasswordTextfield.shake()
}
else{
registerButton.setTitle("Registering user...", forState: UIControlState.Normal)
registerButton.alpha = 0.20
registerButton.enabled = false
registerUser()
}
}


First: Can I make this code smaller, on easier? And second, I want the user only to start
registerUser()
if all UITextField has text, and
usernameTextField
and
passwordTextField
has character count over 6. Also how to fix that
passwordTextField
and
retypepasswordTextfield
has same text before register? Any suggestions?

Answer

This is a bit better in my opinion:

@IBAction func registerButtonAction(sender: AnyObject) {
    let validInput = true
    let allTextFields = [fullnameTextField, usernameTextfield, emailTextfield, passwordTextfield, retypepasswordTextfield]
    for textField in allTextFields {
        if textField.text == "" {
            validInput = false
            textField.shake()
        }
    }

    let theTextFieldsWithMin6Characters = [usernameTextfield, passwordTextfield]
    for textField in theTextFieldsWithMin6Characters {
        if textField.text?.characters.count < 6 {
            validInput = false
            textField.shake()
        }
    }
    if passwordTextfield.text != retypepasswordTextfield.text {
        validInput = false
        retypepasswordTextfield.shake()
    }

    if validInput {
        registerButton.setTitle("Registering user...", forState: UIControlState.Normal)
        registerButton.alpha = 0.20
        registerButton.enabled = false
        registerUser()
    }
}
Comments