quill icon indicating copy to clipboard operation
quill copied to clipboard

how to control the maximum length of the html

Open maku opened this issue 10 years ago • 22 comments

I would like to know if it possible to control the maximum length of the html code (e.g. set a length property).

maku avatar May 21 '16 14:05 maku

You mean setting the maximum number of characters than can be typed into the Quill? Like <textarea> maxlength property?

jhchen avatar May 21 '16 22:05 jhchen

Yes exactly

maku avatar May 22 '16 14:05 maku

There's no built in configuration. You can check the length with getLength() but I don't have a good recommendation for preventing addition of content when the limit is reached.

jhchen avatar May 23 '16 05:05 jhchen

Was able to do this with the following code:

var limit = 10;

quill.on('text-change', function (delta, old, source) {
  if (quill.getLength() > limit) {
    quill.deleteText(limit, quill.getLength());
  }
});

trigun539 avatar Nov 09 '16 19:11 trigun539

Hello. Has anyone got a solution for max-lines behavior? I believe it would be more complex than max-length, and would involve counting by newlines in Deltas with the following rejecting anything below max allowed newlines. It would be great if someone faced such problem and solved it.

StreetStrider avatar May 31 '18 19:05 StreetStrider

I think this solution is incomplete. What happens if user tries to add text in the middle? The solution provided by @trigun539 won't be valid because text will be deleted from the end if I'm not mistaken.

franverona avatar Jul 13 '18 13:07 franverona

Hi everybody, we've found a solution in React that we are content with.

<ReactQuill
    onKeyDown={this.checkCharacterCount}
    onChange={(value) => this.props.onChange(value)}
/>

checkCharacterCount = (event) => {
    if (this.getCharacterText().length > this.props.maxCharacters && event.key !== 'Backspace') {
        event.preventDefault();
    }
}

if the max length of characters is reached, onChange won't be fired.

IanOnFire avatar Nov 28 '18 11:11 IanOnFire

That's a workaround, not a solution. If it's working for you, it's OK. But the purpose of editor (Quill) is to release you from opting in editable area in such crude manners. Too many parts potentially can be broken. Quill API is required.

StreetStrider avatar Nov 28 '18 13:11 StreetStrider

This one works regardless where the text is inserted (doesn't handle formatted pasted content)

const limit = 10; 
quill.on('text-change', function (delta, old, source) {
    if (quill.getLength() <= limit) {
        return;
    }   
    const { ops } = delta;
    let updatedOps;
    if (ops.length === 1) {
        // text is inserted at the beginning
        updatedOps = [{ delete: ops[0].insert.length }]; 
    } else {
        // ops[0] == {retain: numberOfCharsBeforeInsertedText}
        // ops[1] == {insert: "example"}
        updatedOps = [ops[0], { delete: ops[1].insert.length }]; 
    }   
    quill.updateContents({ ops: updatedOps }); 
});

@jhchen It's fine if it's not a good recommendation, at least maybe point us in the right direction. It will save some folks some time hacking around.

nvlled avatar Dec 15 '18 08:12 nvlled

If anyone comes across this and wants a character counter, here's one I threw together. All you need is a div with the class ".character-count".

$('.character-count').text((characterLimit - quill.getLength()) + " Characters Remaining");

You can put this right under the quill.on of the above method and it will work. I spent way too much time on this so I hope it helps someone!

Edit: Just set your characterLimit variable to whatever you want your limit to be +1. Mine is 801 and it's a perfect 800 character limit counting down to zero.

bjgaynor avatar Oct 10 '19 23:10 bjgaynor

This one works regardless where the text is inserted (doesn't handle formatted pasted content)

const limit = 10; 
quill.on('text-change', function (delta, old, source) {
    if (quill.getLength() <= limit) {
        return;
    }   
    const { ops } = delta;
    let updatedOps;
    if (ops.length === 1) {
        // text is inserted at the beginning
        updatedOps = [{ delete: ops[0].insert.length }]; 
    } else {
        // ops[0] == {retain: numberOfCharsBeforeInsertedText}
        // ops[1] == {insert: "example"}
        updatedOps = [ops[0], { delete: ops[1].insert.length }]; 
    }   
    quill.updateContents({ ops: updatedOps }); 
});

@jhchen It's fine if it's not a good recommendation, at least maybe point us in the right direction. It will save some folks some time hacking around.

I was getting infinite loops with this one if I pasted in large amounts of text.

Here is a simpler solution I came up with: Just set the contents back to oldContents if the maxLength is exceeded

    (delta, oldContents) => {
      let html = quill.root.innerHTML;
      let length = html.length;

      if (maxLength && maxLength < length) {
        quill.setContents(oldContents);
      } else {
        // ...do other stuff
      }

Note: I am using the innerHTML to determine length, but you could just look at the text length instead if that suits your needs.

seanjrankin avatar Apr 01 '20 20:04 seanjrankin

@IanOnFire I tried using your implementation, but its says getCharacterText() is not a function

Having trouble in controlling the maximum character length in react ? Isn't there a solid solution provided by the editor itself without workarounds ?

Senelith avatar Apr 28 '20 07:04 Senelith

Here's a solution with a module. It works only if you have history module enabled :

Quill.register('modules/maxlength', function(quill, options) {

    quill.on('text-change', function(e) {
        
            let size = quill.getText();
            if (size.length > options.value)
                quill.history.undo();

    });

});

Then you have to specify your module like that :

var editor = new Quill(container, { modules: 
                                                { 
                                                    maxlength : {value : 10},
                                                    history: { delay: 100, userOnly: true }  
                                                }
                                            });

The lone problem with this solution is when you try to copy and paste. If what you try to copy makes your content longer than the max length, your copy is cancelled. The best would be to allow copying only what fits. It should not be hard to code this behaviour with clipboard module.

kamel-boughaleb avatar May 08 '20 15:05 kamel-boughaleb

This one works regardless where the text is inserted (doesn't handle formatted pasted content)

const limit = 10; 
quill.on('text-change', function (delta, old, source) {
    if (quill.getLength() <= limit) {
        return;
    }   
    const { ops } = delta;
    let updatedOps;
    if (ops.length === 1) {
        // text is inserted at the beginning
        updatedOps = [{ delete: ops[0].insert.length }]; 
    } else {
        // ops[0] == {retain: numberOfCharsBeforeInsertedText}
        // ops[1] == {insert: "example"}
        updatedOps = [ops[0], { delete: ops[1].insert.length }]; 
    }   
    quill.updateContents({ ops: updatedOps }); 
});

@jhchen It's fine if it's not a good recommendation, at least maybe point us in the right direction. It will save some folks some time hacking around.

I was getting infinite loops with this one if I pasted in large amounts of text.

Here is a simpler solution I came up with: Just set the contents back to oldContents if the maxLength is exceeded

    (delta, oldContents) => {
      let html = quill.root.innerHTML;
      let length = html.length;

      if (maxLength && maxLength < length) {
        quill.setContents(oldContents);
      } else {
        // ...do other stuff
      }

Note: I am using the innerHTML to determine length, but you could just look at the text length instead if that suits your needs.

How to get the old content in angular 8 - if i am using $event in event emitter

sliceh avatar Aug 28 '20 05:08 sliceh

There isn't solution for this one yet ?

nashpaw avatar Mar 16 '21 05:03 nashpaw

still no such feature?

sarunzn avatar Apr 20 '22 13:04 sarunzn

still no such feature?

I'd also expect to a max-length feature

miriamso avatar Nov 23 '22 12:11 miriamso

Also done it with this:

if (q) {
  if (currentLength > props.maxLength) {
    const currentLength = q?.root.innerHTML.length || 0;
    q?.deleteText(props.maxLength, q.getLength());

    console.log(q.root.innerHTML);
  } else {
    inputValue.value = q.root.innerHTML;
  }
}

But even if I set my props.maxLength to 20 if I start adding new lines text is wrapped with <p><p> for every line and I end up with more than 20 (i got up to 81) so this is not a real solution

toni-michel avatar Jan 24 '24 13:01 toni-michel

Register custom module

  quill.register('modules/maxlength', function (instance, options) {
    if (!('value' in options)) {
      return;
    }
    instance.on('text-change', () => {
      const text = instance.getText();
      if (text.length - 1 > options.value) {
        instance.history.undo();
      }
    });
  });
const maxLengthModule = this.maxLength
  ? {
      history: { delay: 0 },
      maxlength: { value: this.maxLength }
    }
  : {};

When init set modules

  modules: {
    ...modules,
    ...maxLengthModule
  }

ezzabuzaid avatar Feb 19 '24 14:02 ezzabuzaid

Why is it Closed? Nobody needs a proper implementation for a common maxLength attribute?

ayuzvyak avatar Feb 13 '25 05:02 ayuzvyak