Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift check if textview is empty

Tags:

ios

swift

I wonder how I proper check if a uitextview is empty.

Right now I have a validation fucntion which does the check:

if let descText = myTextView.text {
    if descText.isEmpty {
        descErrorLabel.isHidden = false
    } else {
        descErrorLabel.isHidden = true
    }
}

It this enough to prevent the user from sending an empty textview or must I check of whitespaces also, something like:

stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
like image 376
user2636197 Avatar asked Oct 13 '16 12:10

user2636197


People also ask

How to check if text field is Empty Swift?

Basic Swift Code for iOS Apps Follow the below steps. 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.

How to check multiple text field is Empty in Swift?

text is nil. So, when there is no text, field. text == nil , doing field.

How check if String is empty or nil in Swift?

To check if string is empty in Swift, use the String property String. isEmpty . isEmpty property is a boolean value that is True if there are no any character in the String, or False if there is at least one character in the String.

How do you check if a textField is empty or not?

If you have a text field, you normally want a user to enter in something into the text field. So Java allows us to check if a text field is empty or not through the isEmpty() function. You can then do anything after this including prompt the user to enter in something or whatever.


1 Answers

You could roll it all up into something like this...

func validate(textView textView: UITextView) -> Bool {
    guard let text = textView.text,
        !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
        // this will be reached if the text is nil (unlikely)
        // or if the text only contains white spaces
        // or no text at all
        return false
    }

    return true
}

Then you can validate any UITextView like...

if validate(textView: textView) {
    // do something
} else {
    // do something else
}
like image 55
Fogmeister Avatar answered Oct 02 '22 04:10

Fogmeister