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

问题描述 投票:0回答:2

我在使用 CKEditor 伴随着 CKFinder). 我需要在存储到数据库之前,验证它所渲染的内容,如果CKEditor渲染的内容是空白的,那么就会出现验证违规信息。

如果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>

这实际上代表了一些空格和新行字符,而这些字符是无法通过简单的服务器端函数来修剪的。那么在这种情况下,有什么办法进行验证呢?

java html ckeditor trim ckfinder
2个回答
0
投票

我是一个巨大的书呆子,为此我提出了一个小建议。基本上得到CKEditor的值,把它吐到一个空闲的DIV中,用jQuery得到该内容的长度,然后把它比作0。

我做了一个 jsfiddle 例子,它使用了一个可内容的DIV,用于CKFinder和扔掉的同时。下面是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();
});

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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.