How to check if a text field is empty or not in swift

SwiftTextbox

Swift Problem Overview


I am working on the code below to check the textField1 and textField2 text fields whether there is any input in them or not.

The IF statement is not doing anything when I press the button.

 @IBOutlet var textField1 : UITextField = UITextField()
 @IBOutlet var textField2 : UITextField = UITextField()
 @IBAction func Button(sender : AnyObject) 
  {

    if textField1 == "" || textField2 == "" 
      {

  //then do something

      }  
  }

Swift Solutions


Solution 1 - Swift

Simply comparing the textfield object to the empty string "" is not the right way to go about this. You have to compare the textfield's text property, as it is a compatible type and holds the information you are looking for.

@IBAction func Button(sender: AnyObject) {
    if textField1.text == "" || textField2.text == "" {
        // either textfield 1 or 2's text is empty
    }
}

Swift 2.0:

Guard:

guard let text = descriptionLabel.text where !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

if:

if let text = descriptionLabel.text where !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}

Swift 3.0:

Guard:

guard let text = descriptionLabel.text, !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

if:

if let text = descriptionLabel.text, !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}

Solution 2 - Swift

Better and more beautiful use

 @IBAction func Button(sender: AnyObject) {
    if textField1.text.isEmpty || textField2.text.isEmpty {
      
    }
}

Solution 3 - Swift

another way to check in realtime textField source :

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }
    
 func yourNameFunction(sender: UITextField) {
    
    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }

Solution 4 - Swift

if let ... where ... {

Swift 3:

if let _text = theTextField.text, _text.isEmpty {
    // _text is not empty here
}

Swift 2:

if let theText = theTextField.text where !theTextField.text!.isEmpty {
    // theText is not empty here
}

guard ... where ... else {

You can also use the keyword guard :

Swift 3:

guard let theText = theTextField.text where theText.isEmpty else {
    // theText is empty
    return // or throw
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Swift 2:

guard let theText = theTextField.text where !theTextField.text!.isEmpty else {
    // the text is empty
    return
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

This is particularly great for validation chains, in forms for instance. You can write a guard let for each validation and return or throw an exception if there's a critical error.

Solution 5 - Swift

As now in swift 3 / xcode 8 text property is optional you can do it like this:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

or:

if (textField.text?.isEmpty ?? true) {
    // is empty
}

Alternatively you could make an extenstion such as below and use it instead:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}

Solution 6 - Swift

A compact little gem for Swift 2 / Xcode 7

@IBAction func SubmitAgeButton(sender: AnyObject) {

    let newAge = String(inputField.text!)        
    
if ((textField.text?.isEmpty) != false) {
        label.text = "Enter a number!"
    }
    else {
        label.text = "Oh, you're \(newAge)"
        
        return
    }
    
    }

Solution 7 - Swift

Maybe i'm a little too late, but can't we check like this:

   @IBAction func Button(sender: AnyObject) {
       if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {

       }
    }

Solution 8 - Swift

use this extension

extension String {
    func isBlankOrEmpty() -> Bool {

      // Check empty string
      if self.isEmpty {
          return true
      }
      // Trim and check empty string
      return (self.trimmingCharacters(in: .whitespaces) == "")
   }
}

like so

// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.isEnabled = !text.isBlankOrEmpty()

Solution 9 - Swift

Okay, this might be late, but in Xcode 8 I have a solution:

if(textbox.stringValue.isEmpty) {
    // some code
} else {
    //some code
}

Solution 10 - Swift

I used UIKeyInput's built in feature hasText: docs

For Swift 2.3 I had to use it as a method instead of a property (as it is referenced in the docs):

if textField1.hasText() && textField2.hasText() {
    // both textfields have some text
}
    

Solution 11 - Swift

Swift 4.x Solution


@IBOutlet var yourTextField: UITextField!

 override func viewDidLoad() {
     ....
     yourTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
  }

 @objc func actionTextFieldIsEditingChanged(sender: UITextField) {
     if sender.text.isEmpty {
       // textfield is empty
     } else {
       // text field is not empty
     }
  }

Solution 12 - Swift

Swift 4.2

You can use a general function for your every textField just add the following function in your base controller

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false
        
    }else{
        return true
    }
}

Solution 13 - Swift

Swift 4/xcode 9

IBAction func button(_ sender: UIButton) {
        if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
                ..............
        }
}

Solution 14 - Swift

I just tried to show you the solution in a simple code

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}

Solution 15 - Swift

It's too late and its working fine in Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }

Solution 16 - Swift

Easy way to Check

if TextField.stringValue.isEmpty {

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGokhan DilekView Question on Stackoverflow
Solution 1 - SwiftBrian TracyView Answer on Stackoverflow
Solution 2 - SwiftUnRewaView Answer on Stackoverflow
Solution 3 - SwiftraphaelView Answer on Stackoverflow
Solution 4 - SwiftAlexandre G.View Answer on Stackoverflow
Solution 5 - SwiftLeszek SzaryView Answer on Stackoverflow
Solution 6 - SwiftEdisonView Answer on Stackoverflow
Solution 7 - SwiftjfredsilvaView Answer on Stackoverflow
Solution 8 - SwiftDan AlboteanuView Answer on Stackoverflow
Solution 9 - SwiftCorey KennedyView Answer on Stackoverflow
Solution 10 - SwiftAlex BrashearView Answer on Stackoverflow
Solution 11 - SwiftHemangView Answer on Stackoverflow
Solution 12 - SwiftRana Ali WaseemView Answer on Stackoverflow
Solution 13 - SwiftlaplaceView Answer on Stackoverflow
Solution 14 - SwiftNaveed AhmadView Answer on Stackoverflow
Solution 15 - Swiftjoel prithiviView Answer on Stackoverflow
Solution 16 - SwiftAli Asgher LakkadshawView Answer on Stackoverflow