如何修剪CKEditor渲染的空格和换行?

时间:2012-12-18 06:42:37

标签: java html ckeditor trim ckfinder

我正在使用CKEditor(以及CKFinder)。我需要在存储到数据库之前验证它呈现的内容。

如果CKEditor呈现的内容为空,则应显示验证违规消息。这可以在服务器端轻松完成,但如果用户进入空格和新行,那么应该对其进行修剪,并且不应将任何内容插入到违反验证规则的数据库中。

只需在服务器端使用String.trim()(关于Java)等函数就可以,因为CKEditor会呈现HTML。如果我只输入一些空格和换行符,那么渲染的HTML看起来就像下面这样。

<p>            
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   
</p>

<p>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</p>

实际上代表了一些空白字符和新行字符,这些字符无法通过简单地使用服务器端功能进行修剪。那么在这种情况下执行验证的方法是什么?

2 个答案:

答案 0 :(得分:0)

我是一个巨大的书呆子,对此提出了一个小小的建议。基本上得到CKEditor值,将它呕吐成一次性DIV,用jQuery获取该内容的长度并将其与0进行比较。

我制作了一个jsfiddle示例,它同时为CKFinder和一次性使用了一个可信的DIV。这是JavaScript,我希望你能得到这个想法。如果没有,请提出问题,我会尝试澄清我的扭曲代码。

$(function() {
    // this just keeps track of the contenteditable
    // replace with your submit or whatever event
    $('body').on('focus', '[contenteditable]', 
            function() {
                var $this = $(this);
                $this.data('before', $this.html());
                return $this;
            }).on('blur keyup paste', '[contenteditable]', function() {
                var $this = $(this);
                if ($this.data('before') !== $this.html()) {
                    $this.data('before', $this.html());
                    $this.trigger('change');
                }
                return $this;
            });
    $('body').on('change', function() {
       validate();
    });

    // This actually validates the string as 0-rendering or not.
    function validate() {

        // Replace this text getter with getting the CKE content
        // Then vomit it into a DIV like check and then get it again.
        // just keep #check invisible with CSS.
        var text = $('#check').text();
        var l = text.trim().length;

        // if length is 0, it renders as whitespace only
        // I show a message to whine about that
        if (l === 0) {
            $('#aaa').text("DOES NOT PASS");    
        }
        else {
             $('#aaa').text("PASS");   
        }   
    }
    validate();
});

答案 1 :(得分:0)

只要将文本编辑器字符串传递给此方法(如果它返回true),则意味着我们有空字符串,没有实际的文本内容。

public boolean validateSpace(String str) {
        if (str != null) {
            String replaceStr = str.replace("&nbsp;", "").replace("<p>", "").replace("</p>", "").replace("<br>", "").replace("<br />", "");
            if (replaceStr == null || replaceStr.trim().isEmpty()) {
                return true;
            }
        }
        return false;
    }
相关问题