user2636197 user2636197 - 1 month ago 15
Swift Question

swift check if textview is empty

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

Answer

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
}
Comments