How to check whether CKEditor has some text in it?

Viewed 36053

I have an HTML form with a few fields. One of them is a textarea managed by CKEditor.

When the user wants to submit the form, I want to check whether he entered values in all the fields.

I know how I can check if CKEditor control has anything in it, but it could be "empty" HTML tags without any text in it.

How do I check for text?

Server side I'm using something like PHP's trim(strip_tags($content)), so I'd like to have the same in JavaScript.

A solution using jQuery would also be usable.

6 Answers

CKEditor 5 - Classic editor

This is an old question but, since it's one of the first results in google, i think it would be helpful to update the answer for the latest versions of ckeditor, in my case ckeditor 5 version 11.0.1

The problem with ckeditor 5 is even when it's/looks empty, when submitting the form, it does'nt send an empty value as you may expect, but instead it send this string :

<p>&nbsp;</p>

It's not what you want, especially when you want set some validations rules on the server side.

To avoid this headache, i use this snippet of code based on light-flight answer:

$(document).ready(function() {

    var editorContainer = document.querySelector('#editor');

    var check_if_empty = function(val) {

        return $.makeArray($(val)).every(function(el) {

            return el.innerHTML.replace(/&nbsp;|\s/g, '').length === 0;
        });
    };

    var clear_input_if_empty_content = function(input) {

        var $form = $(input).parents('form');

        $form.on('submit', function() {

            if (check_if_empty($(input).val())) {

                $(input).val('');
            }
        });
    };

    ClassicEditor.create( editorContainer )
        .then(function(editor) {
            clear_input_if_empty_content(editorContainer)
        })
        .catch(function(error) {
            console.log(error);
        });
});

<script>
CKEDITOR.replace('messagechat');

var feedback = CKEDITOR.instances.messagechat.document.getBody().getChild(0).getText(); 
// get Data
alert(feedback);
</script>
Related