thumbtackthief
thumbtackthief

Reputation: 6211

Check if Swift text field contains non-whitespace

This is an extension, not a duplicate, of How to check if a text field is empty or not in swift

The given answer,

@IBAction func Button(sender: AnyObject) {
    if textField1.text != ""  {
        // textfield 1 
    }
}

does not work for me, i.e., the if-loop is triggered even when nothing is entered in the text field. (I have modified it from the original because I'm looking to trigger the code only when the field contains text).

The second answer

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

    }
}

comes much closer, but it accepts strings like " " as not empty. I could build something myself, but is there a function that will check if a string contains something other than whitespace?

Upvotes: 85

Views: 51293

Answers (13)

stackich
stackich

Reputation: 5237

Swift 5.8

Probably the cleanest solution:

extension String {
    func isEmptyOrWhitespace() -> Bool {
        return self.trimmingCharacters(in: .whitespaces).isEmpty
    }
}

Upvotes: 2

AnderCover
AnderCover

Reputation: 2661

In Swift 5.7.2 (but probably earlier) CharacterSet conforms to SetAlgebra.

So instead of creating a copy of the string with trimmingCharacters(in:) and .whitespacesAndNewlines it is possible to create a CharacterSet from the string using init(charactersIn:) and check that it is not a subset of .whitespacesAndNewlines

For example :

extension String {
    func hasOnlyCharachersIn(_ characterSet: CharacterSet) -> Bool {
        let charactersInSelf = CharacterSet(charactersIn: self)
        return charactersInSelf.isSubset(of: characterSet)
    }
    
    var hasNonWhitespaceCharacters: Bool {
        !hasOnlyCharachersIn(.whitespacesAndNewlines)
    }
}

produces in a playground:

var testString = ""
testString.hasNonWhitespaceCharacters // false

testString = " "
testString.hasNonWhitespaceCharacters // false

testString = "\t"
testString.hasNonWhitespaceCharacters // false

testString = " \t\n"
testString.hasNonWhitespaceCharacters // false

testString = "\n"
testString.hasNonWhitespaceCharacters // false

testString = "foo"
testString.hasNonWhitespaceCharacters // true

testString = "foo bar"
testString.hasNonWhitespaceCharacters // true

testString = "foo\tbar"
testString.hasNonWhitespaceCharacters // true

testString = "foo bar\tbaz\n"
testString.hasNonWhitespaceCharacters // true

Upvotes: -1

Prabakaran Muthusamy
Prabakaran Muthusamy

Reputation: 175

Method

 func trim() -> String {
    return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}

Use

if textField.text.trim().count == 0 {
    // Do your stuff
}

Upvotes: 2

akashivskyy
akashivskyy

Reputation: 45180

This answer was last revised for Swift 5.2 and iOS 13.5 SDK.


You can trim whitespace characters from your string and check if it's empty:

if !textField1.text.trimmingCharacters(in: .whitespaces).isEmpty {
    // string contains non-whitespace characters
}

You can also use .whitespacesAndNewlines to remove newline characters too.

Upvotes: 195

coders
coders

Reputation: 2477

Answer with a picture in case you need a demo

// MY FUNCTIONS
private func checkMandatoryFields(){

    //CHECK EMPTY OR SPACES ONLY FIELDS
    if let type = typeOutle.text, let name = nameOutlet.text, let address = addressOutlet.text, type.trimmingCharacters(in: .whitespaces).isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty || address.trimmingCharacters(in: .whitespaces).isEmpty {
        print("Mandatory fields are: ")
        errorDisplay(error: "Mandatory fields are: Type, Name, Address.")
        return
    }

}

enter image description here

Upvotes: 1

Ahmed Safadi
Ahmed Safadi

Reputation: 4590

swift 4.2

@IBAction func checkSendButton(_ sender: UITextField) {
    if((sender.text?.count)! > 0 && !(sender.text!.trimmingCharacters(in: .whitespaces)).isEmpty){
        self.sendButton.isEnabled = true
    }
    else{
        self.sendButton.isEnabled = false
    }
}

Upvotes: -1

BigMountainStudio.com
BigMountainStudio.com

Reputation: 17570

Swift 4.2

Extension for String is empty or whitespace

extension String {
    func isEmptyOrWhitespace() -> Bool {
        
        // Check empty string
        if self.isEmpty {
            return true
        }
        // Trim and check empty string
        return (self.trimmingCharacters(in: .whitespaces) == "")
    }
}

The original poster's code is checking text on a textfield which is optional. So he will need some code to check optional strings. So let's create a function to handle that too:

Extension for Optional String is nil, empty or whitespace

extension Optional where Wrapped == String {
    func isEmptyOrWhitespace() -> Bool {
        // Check nil
        guard let this = self else { return true }
        
        // Check empty string
        if this.isEmpty {
            return true
        }
        // Trim and check empty string
        return (this.trimmingCharacters(in: .whitespaces) == "")
    }
}

Upvotes: 13

Dylan
Dylan

Reputation: 131

Answer in swift 4:

extension String {
    func isEmptyOrWhitespace() -> Bool {
        if(self.isEmpty) {
            return true
        }
        return (self.trimmingCharacters(in: NSCharacterSet.whitespaces) == "")
    }
}

Upvotes: 5

Leo Dabus
Leo Dabus

Reputation: 236370

extension StringProtocol where Index == String.Index {
    var isEmptyField: Bool {
        return trimmingCharacters(in: .whitespaces) == ""
    }
}


if yourTextField.text.isEmptyField {
    // Field is empty
} else {
    // Field is NOT empty
}

Upvotes: 4

ronatory
ronatory

Reputation: 7324

akashivskyy answer in Swift 3.0:

let whitespaceSet = CharacterSet.whitespaces
if !str.trimmingCharacters(in: whitespaceSet).isEmpty {
  // string contains non-whitespace characters
}

Upvotes: 5

KimJ
KimJ

Reputation: 29

Answer in Swift 3.*, considers newlines, tabs

extension String {

    var containsNonWhitespace: Bool {
        return !self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

}

Upvotes: 2

Vishnu Gupta
Vishnu Gupta

Reputation: 95

Answer in Swift 3.0

if stringValue.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
{}

Upvotes: 3

Doolali
Doolali

Reputation: 1006

Below is the extension I wrote that works nicely, especially for those that come from a .NET background:

extension String {
    func isEmptyOrWhitespace() -> Bool {

        if(self.isEmpty) {
            return true
        }

        return (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "")
    }
}

Upvotes: 25

Related Questions