How to check if a text field is empty or not in 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
}
Checking if textfields are empty Swift
This post is given a good answer (it's a pity it has no "accepted" mark). Use (self.field.text?.isEmpty ?? true)
.
Assume your textField
is declared as:
@IBOutlet weak var textField: UITextField!
You can check its emptiness with:
if textField.text?.isEmpty ?? true {
print("textField is empty")
} else {
print("textField has some text")
}
To use the variables in your edited post:
let userEmail = userEmailTextField.text;
// Check for empty fields
if userEmail?.isEmpty ?? true {
// Display alert message
return;
}
or:
// Check for empty fields
if userEmailTextField.text?.isEmpty ?? true {
// Display alert message
return;
}
Elegant way to check if UITextField is empty
How about extending UITextField
…
extension UITextField {
var isEmpty: Bool {
if let text = textField.text, !text.isEmpty {
return false
}
return true
}
}
so then…
if myTextField.isEmpty {
}
how to check textfield is not empty and button enable
I have attached the code how to check that textFiled is empty or not
let txtField = UITextField()
txtField.text = "testing"
if txtField.text != "" {
btn_Pause.isEnabled = true
} else {
btn_Pause.isEnabled = false
}
-> Using isEmpty function
if txtField.text?.isEmpty == true {
btn_Pause.isEnabled = false
} else {
btn_Pause.isEnabled = true
}
-> Using character count
if txtField.text?.count ?? 0 > 0 {
btn_Pause.isEnabled = true
} else {
btn_Pause.isEnabled = false
}
Checking if text field is empty
Try this,
if(userEmail == "" || userPassword == "" || userRepeatPassword == "")
{
//Do Something
}
(or)
if(userEmail == "" && userPassword == "" && userRepeatPassword == "")
{
//Do Something
}
Swift give specific text if textField is empty
The problem is you always get an empty string that's not nil. You can correct that as following:
let text = (textField.text ?? "").isEmpty ? "abc" : textField.text
Swift - Check textfield empty or not
Once you defined your "email", you can use the string to count its characters, like so:
guard let email = self.usertxt2.text, email.count != 0 else {
alert.message = "Please enter your email"
return
}
also, you can use the built-in variable
isEmpty
guard let email = self.usertxt2.text, !email.isEmpty else {
alert.message = "Please enter your email"
return
}
But I think it's better to validate email using REGEX
let email = self.usertxt2.text
guard email.count > 0 else { print("Email is required")
return
}
do {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if try NSRegularExpression(pattern: emailRegEx, options: .caseInsensitive).firstMatch(in: value, options: [], range: NSRange(location: 0, length: value.count)) == nil {
print("Invalid email")
}
} catch {
print("Invalid email")
}
How to detect if a textfield is empty in swift?
Fixing the other answer:
txtSitReach.addTarget(self, action: #selector(textDidChange), forControlEvents: .EditingChanged)
func textDidChange(textField: UITextField) {
doneSitReachButton.enabled = !txtSitReach.text!.isEmpty
}
How to check if a textFieldView is empty or has no spaces?
Just check if the trimmed string is empty
let isEmpty = str.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).isEmpty
You can even put it in an String
extension:
extension String {
var isReallyEmpty: Bool {
return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).isEmpty
}
}
It even works for a string like var str = " "
(that has spaces, tabs and zero-width spaces).
Then simply check textField.text?.isReallyEmpty ?? true
.
If you wanna go even further (I wouldn't) add it to an UITextField
extension:
extension UITextField {
var isReallyEmpty: Bool {
return text?.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).isEmpty ?? true
}
}
Your code becomes textField.isReallyEmpty
.
Related Topics
What Is the Practical Use of Nested Functions in Swift
Swift 2 Migration Savecontext() in Appdelegate
Binding an Element of an Array of an Observableobject:'Subscript(_:)' Is Deprecated
Pointers, Pointer Arithmetic, and Raw Data in Swift
Can't Create a Range in Swift 3
Is There an Alternative to Initialize() in MACos Now That Swift Has Deprecated It
How to Update Text Using Timer in Swiftui
Swift: How to Create External Interface for Static Library (Public Headers Analog in Objective-C .H)
Swift/Uiview/Drawrect - How to Get Drawrect to Update When Required
Which Format File for 3D Model Scenekit/Arkit Better to Use
In Swift, How to Get Memory Back to Normal After an Skscene Is Removed
Swift: How to Call Cckeyderivationpbkdf from Swift
Differencebetween Swift 2.0 Do-Try-Catch and Regular Java/C#/C++ Exceptions
How to Set Top Left and Right Corner Radius with Desired Drop Shadow in Uitabbar
When to Use [Self] VS [Weak Self] in Swift Blocks