简体   繁体   English

如何检查富文本编辑器内容是否为空?

[英]How to check if rich text editor content is empty?

I have a blog with posts.我有一个有帖子的博客。 I also have a rich text editor ( Quill ).我还有一个富文本编辑器 ( Quill )。

Is it possible to check if the rich text editor has empty content?是否可以检查富文本编辑器是否有空内容?

I use Quill (with React, Express JS, MongoDB) and I want to somehow prevent storing the empty value in the database.我使用 Quill(与 React、Express JS、MongoDB)并且我想以某种方式防止将空值存储在数据库中。

The problem is that if I add spaces into the editor the Quill will generate empty paragraphs.问题是,如果我在编辑器中添加空格, Quill将生成空段落。 So no content only empty paragraphs.所以没有内容只有空段落。 With the normal input field, I can check for the empty string but what if I have a rich text editor?使用普通输入字段,我可以检查空字符串,但如果我有富文本编辑器怎么办?

Problem:问题:

<p>                     </p>

or even worse甚至更糟

<p>                            </p><p><br></p><p><br></p><p>       </p>

I don't really want to save this into the database.我真的不想将其保存到数据库中。 Because I don't want to have empty posts.因为我不想有空帖。 How can I solve this issue?我该如何解决这个问题? Can be the solution to somehow check for empty paragraph?.. but what about the <br> tag?可以以某种方式检查空段落的解决方案吗?..但是<br>标签呢?

Please open this codesandbox and just enter bunch of spaces and click on the button.请打开这个codesandbox,输入一堆空格,然后点击按钮。 Open console and you'll see output of the editor.打开控制台,你会看到编辑器的output。

codesandbox: https://dxqhq.codesandbox.io/ codesandbox: https://dxqhq.codesandbox.io/

Thank you very much非常感谢你

as I understand you only want to save user input only if contains text so you have to clean the user input from HTML then check the output length据我了解,您只想在包含文本时才保存用户输入,因此您必须从 HTML 清除用户输入,然后检查 output 长度

var regex = /(<([^>]+)>)/ig
body = "<p>test</p>"
hasText = !!body.replace(regex, "").length;
if(hasText) save()

This worked for me so it wouldn't escape images.这对我有用,所以它不会逃避图像。

function isQuillEmpty(value: string) {
   if (value.replace(/<(.|\n)*?>/g, '').trim().length === 0 && !value.includes("<img")) {
      return true;
    }
      return false;
    }

You can check if a QuillJS delta object is empty or has whitespaces only by iterating through the object's ops property and checking the insert value of each operation.您可以通过遍历对象的ops属性并检查每个操作的insert值来检查QuillJS delta object是否为空或是否有空格。 If all insert values are whitespace characters or the ops array is empty, then the delta object is considered empty or has whitespaces only.如果所有insert值都是空白字符或ops数组为空,则增量 object 被认为是空的或只有空白。

Here is the function that checks if the delta object is empty or has whitespaces only:这是 function 检查增量 object 是否为空或只有空格:

isDeltaEmptyOrWhitespace(delta) {
    if (delta.ops.length === 0) {
        return true;
    }
    for (let i = 0; i < delta.ops.length; i++) {
        if (delta.ops[i].insert.trim() !== '') {
            return false;
        }
    }
    return true;
}

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM