Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple textfields are empty - iOS with Swift

Tags:

ios

swift

So, I'm developing an app signUp screen. I'm trying to check each field on the signUp screen to see if it's empty, and if it is, display an error message in a label to the user. I've been using a chain of else-ifs

    if ((self.firstNameField.text?.isEmpty) != nil) {
        errorLabel.text = "first name missing"
        errorLabel.hidden = false
    }

    else if ((self.lastNameField.text?.isEmpty) != nil) {
        errorLabel.text = "last name missing"
        errorLabel.hidden = false
    }

    else if ((self.emailField.text?.isEmpty) != nil) {
        errorLabel.text = "email missing"
        errorLabel.hidden = false
    }

    else if ((self.passwordField.text?.isEmpty) != nil) {
        errorLabel.text = "password missing"
        errorLabel.hidden = false
    }

    else if ((self.confirmPasswordField.text?.isEmpty) != nil) {
        errorLabel.text = "password confirmation missing"
        errorLabel.hidden = false
    }

    else if (self.passwordField.text != self.confirmPasswordField.text) {
        errorLabel.text = "Passwords don't match, try again!"
        errorLabel.hidden = false
    } 
    //omitted what happens if there are no fields missing

Now, when I run the application with all the textfields empty, the errorLabel displays the message "first name missing". Putting in a first name and pressing the signup button does nothing. I want it to change to "last name missing", but it stays at "first name missing".

like image 300
Anthony Rossello Avatar asked Dec 11 '22 20:12

Anthony Rossello


1 Answers

The reason this is happening is because you are checking if self.field.text?.isEmpty != nil. You should be checking for (self.field.text?.isEmpty ?? true)

Essentially, you're trying to get the text in the field, and if there is no text, then nil is returned. By using field.text?, you are making the next variable you access nil based on whether field.text is nil. So, when there is no text, field.text == nil, doing field.text?.isEmpty will always return nil.

When there is text, field.text?.isEmpty will not be nil, and will always be false, but nil != false, so the statement will always return false.

To fix this, you should check

if(self.field.text?.isEmpty ?? true)

which essentially means

if((self.field.text?.isEmpty == nil ? true : self.field.text?.isEmpty))

Basically, this will return true if field.text == nil (which would make field.text?.isEmpty nil, making the result true due to the ?? operator), and will also return true if field.text != nil || field.text.isEmpty. It will only return false if self.field.text != nil && !self.field.text.isEmpty.

Another way to write this statement would be

if(self.field.text == nil || self.field.text!.isEmpty)
like image 115
Jojodmo Avatar answered Dec 29 '22 00:12

Jojodmo