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


It’s very easy to check whether text field is empty or not in Swift.

You will first need to check whether text is available or not in text field i.e. it’s not nil, then you will need to check if its present then its empty or not. Assuming myTextField is your text field variable name, you can do the following

if let text = myTextField.text, text.isEmpty {
   // myTextField is not empty here
} else {
   // myTextField is Empty
}

Above code will check if textField is empty or not.

If you want to look at how the text field can be added and checked in details . Follow the below steps.

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “CheckEmptyTextField”

Step 2 − Open Main.storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label.

Step 3 − Add IBOutlet for text field in ViewController, name it textField

@IBOutlet weak var textField: UITextField!

Step 4 − Add IBoutlet for label, it resultLabel

@IBOutlet weak var resultLabel: UILabel!

Step 5 − Add @IBAction for touchUpInside ‘Check’ button as follows

@IBAction func checkTextFeild(_ sender: Any) {
}

Step 6 − In checkTextFeild function we will test whether the textField is empty or not, and show the result in label. Add below code to do so

@IBAction func checkTextFeild(_ sender: Any) {
   if let text = textField.text, text.isEmpty {
      resultLabel.text = "Text field is empty"
   } else {
      resultLabel.text = "Text Field is not empty"
   }
}

Step 7 − Run the project. Click on ‘Check’ button, you should see that the label gets updated saying ‘Text field is empty"’

Step 8 − Type something in textField, now click on ‘Check’ button, you should see that the label gets updated saying ‘Text Field is not empty"’

raja
Published on 11-Sep-2019 11:27:25
Advertisements