vendredi 5 mai 2017

Swift: Multiple conditions in IF statement

I'm currently trying to validate a sign up page using an if statement with multiple conditions.

At the same time, I want to validate the email address with a correct email format.

Below is each field should essentially be checked.

@IBAction func createAccountButton(_ sender: Any) {

    //check if textfields are empty and display alert
    let providedEmailAddress = emailTextField.text
    let isEmailAddressValid = isValidEmailAddress(emailAddressString: providedEmailAddress!)


    if ( isEmailAddressValid || (firstNameTextField.text?.isEmpty)! || (lastNameTextField.text?.isEmpty)! || (usernameTextField.text?.isEmpty)! || (phoneNumberTextField.text?.isEmpty)! || (passwordTextField.text?.isEmpty)!) {
        let alertViewController = SCLAlertView().showInfo("Failed to create account", subTitle: "One or more fields are empty, please check and try again.")
    } else {
        SVProgressHUD.show(withStatus: "Creating account...")
        SVProgressHUD.dismiss(withDelay: 4)
    }
}

The variable isEmailAddressValid is linked to this function I found on this site.

// Check if email address entered is of the valid format
    func isValidEmailAddress(emailAddressString: String) -> Bool {

        var returnValue = true
        let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"

        do {
            let regex = try NSRegularExpression(pattern: emailRegEx)
            let nsString = emailAddressString as NSString
            let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

            if results.count == 0
            {
                returnValue = false
            }

        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            returnValue = false
        }

        return  returnValue
    }

However, when testing I realised when I enter a value in each field except the emailTextfield.text and click to create an account, the else part of the statement is executed.

Moreover when all fields have a value, I would assume the else part of the statement WILL execute, but the 'failed to create an account' alert is displayed instead.

What am I doing wrong and what needs to be changed?

Aucun commentaire:

Enregistrer un commentaire