9

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
Fogmeister
  • 76,236
  • 42
  • 207
  • 306
user2636197
  • 3,982
  • 9
  • 48
  • 69
  • later one is good. – Bista Oct 13 '16 at 12:40
  • http://stackoverflow.com/questions/33036458/how-to-check-uitextfield-is-not-blank-in-swift-2-0-is-there-better-way-to-count/33036724 – Bhavin Bhadani Oct 13 '16 at 12:42
  • I'll suggest personally to check for whiteSpace and New Lines, but can user send " " ? Is it allowed? Does it make sense ? Both approaches are valid, but which one is better is up to the specs. – Larme Oct 13 '16 at 12:47

1 Answers1

16

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
}
Fogmeister
  • 76,236
  • 42
  • 207
  • 306