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

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

      }  
  }

This question is related to swift textbox

The answer is


Easy way to Check

if TextField.stringValue.isEmpty {

}

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

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.


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
}

Better and more beautiful use

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

    }
}

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

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

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

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

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

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
    }

    }

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

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 {

       }
    }

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

Swift 4/xcode 9

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

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
}

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