user6401887
user6401887

Reputation:

How to check if a textFieldView is empty or has no spaces?

textField.text.isEmpty
textField.text != ""

These two functions regard spaces as characters. However, I would like my to recognise when the text field has no spaces or is not empty.

Upvotes: 4

Views: 4253

Answers (3)

Angi
Angi

Reputation: 67

In Swift 4,

extension String {
    var isReallyEmpty: Bool {
        return self.trimmingCharacters(in: .whitespaces).isEmpty
    }
}

Upvotes: 6

fpg1503
fpg1503

Reputation: 7582

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.

Upvotes: 8

user6401887
user6401887

Reputation:

I used this from @Pieter21 's link. It works for as many blank spaces a user could enter.

let myString = TextField.text

let trimmedString = myString!.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)

if trimmedString != "" {
    // Code if not empty
} else {
    // Code if empty
}

Upvotes: 0

Related Questions