Blueprint by Tiny
Return to Tiny.cloud
Return to Tiny.cloudTry TinyMCE for Free
Search by

How to limit characters and set a maxlength with TinyMCE

Joe Robinson

May 2nd, 2022

Written by

Joe Robinson

Category

How-to Use TinyMCE

Is your app struggling under the weight of excessive text entry management? One solution is to keep the character limit and maxlength under control.

Setting up a character limit to keep the text under control stops the viewer from typing excessively. This typing behavior control (through character limits), represents a key design element of both online forms, and micro-blogging platforms like Twitter.

This article explains how to limit characters in the TinyMCE text area. It covers how to set a maxlength, and how to add logic to check if the characters entered into the TinyMCE text area exceed the character limit.

How to set a character limit with TinyMCE

What you need to get started

You don’t need to spend a large amount of time and attention configuring a character limit with TinyMCE. All you need is additional JavaScript to the tinymce.init  content, and to make use of the Wordcount Plugin API .

Setting the TinyMCE max length for character limits

To complete the process, if you haven’t already done so, sign up for a FREE TinyMCE API key. This gives you access to premium plugins for 14 days and also prevents any warning messages appearing in your TinyMCE text area.

Character limits start with tinymce.init

  1.  Open an index.html file, and include the tiny.init script
<script>
    tinymce.init({
      selector: '#mytextarea'
  1.  Add the Wordcount plugin to your list of plugins:
plugins: 'advlist autolink lists link image charmap preview anchor pagebreak code visualchars wordcount',
  1.  Write a function called editor  and include it in the tinymce.init   script:
setup: function(editor) {
	  	var max = 20;
	    editor.on('submit', function(event) {
		  var numChars = tinymce.activeEditor.plugins.wordcount.body.getCharacterCount();
		  if (numChars > max) {
			alert("Maximum " + max + " characters allowed.");
			event.preventDefault();
			return false;
		  }
		});
  1.  Set up a variable called max , and set it as a number with the value of 20
setup: function(editor) {
	  	var max = 20;
}); 
  1.  Add a function event, and set up the tinymce.activeEditor  API with the WordCount Plugin getCharacterCount()  API methods:
setup: function(editor) {
	  	var max = 20;
	    editor.on('submit', function(event) {
		  var numChars = tinymce.activeEditor.plugins.wordcount.body.getCharacterCount();}
);
  1.  Add an  if statement  to evaluate the number of characters typed, and send an alert if the characters exceed the specified max variable:
setup: function(editor) {
	  	var max = 20;
	    editor.on('submit', function(event) {
		  var numChars = tinymce.activeEditor.plugins.wordcount.body.getCharacterCount();
		  if (numChars > max) {
			alert("Maximum " + max + " characters allowed.");
			event.preventDefault();
			return false;
		  }
		});
  1.  Create the textarea tags for TinyMCE along with form and button tags:
<form method="post" action="dump.php">
  <textarea id="mytextarea"></textarea>
  <button>Save</button>
</form>;
  1.  Save the changes, and test out the plugin in your browser.

When typing into the textarea, click the button to check on the text character limit. The alert signals when the max character limit is exceeded:

A character limit alert informing the person typing they must stop

The following is the complete character limit demo.

How to set character limits with React

If you’re using the React framework with TinyMCE, you can limit the number of characters that can appear in the textarea. The React integration with TinyMCE uses the (editor.getContent({ format: 'text' }).length);  API to check the content length. The documentation contains an example of the configuration with React:

function MyComponent({ initialValue, limit }) {
  const sizeLimit = limit ?? 50;
  const [value, setValue] = React.useState(initialValue ?? "");
  const [length, setLength] = React.useState(0);

  const handleInit = (evt, editor) => {
    setLength(editor.getContent({ format: "text" }).length); //A method for retrieving the character count in the textarea
  };

  const handleUpdate = (value, editor) => {
    const length = editor.getContent({ format: "text" }).length;
    if (length <= sizeLimit) {
      setValue(value);
      setLength(length);
    }
  };

  const handleBeforeAddUndo = (evt, editor) => {
    const length = editor.getContent({ format: "text" }).length;
    // note that this is the opposite test as in handleUpdate
    // because we are determining when to deny adding an undo level
    if (length > sizeLimit) {
      evt.preventDefault();
    }
  };

  return (
    <>
      <Editor
        initialValue={initialValue}
        value={value}
        onInit={handleInit}
        onEditorChange={handleUpdate}
        onBeforeAddUndo={handleBeforeAddUndo}
      />
      <p>Remaining: {sizeLimit - length}</p>
    </>
  );
}

Check on the TinyMCE integration with React documentation  for more information. You can also try out the controlled component capabilities with the TinyMCE React demo .

Note: Some quirks exist within the integration. Sometimes, when the character limit is reached:

  • TinyMCE calls the setContent API method
  • The API adds one additional whitespace (a newline character), which counts as a character.
  • The extra character is trimmed away as a result.
  • The result is some small typographical issues.

For instance, if typing the phrase “the quick brown fox jumps over the lazy dog”, if the character limit is reached on the word “fox” at the “o” character, the following occurs:

  1.  “the quick brown fo” changes to “the quick brown f” with the “o” character deleted as the person typing into the text area reaches the character limit.
  2.  The setContent  API method adds one additional whitespace (newline character), and then whitespace is trimmed. The editor state is “the quick brown  f ” at this moment, rapidly becoming “the quick brown f” after the whitespace is trimmed.
  3.  As the viewer keeps typing, adding the “x” in “fox”, the result is “the quick brown fx” as TinyMCE appends the “x” character in place of the trimmed whitespace following the “x” character keypress.

Other quirks to look out for include:

  •  Multiple spaces are replaced with    tags.
    • These appear because HTML collapses multiple spaces into a single space by default. If you intend to store content as HTML in your app or project design, you may need to store content that is larger than how it appears in the editor because of the formatting effects.
  •  Emoji can use up more character spaces.
    • Emoji cannot fit into a single 16-but code unit. Each character that represents the Emoji is counted by the character limit check.

What to check after character limits

When you’ve completed the additions to your index.html file, you can adjust the max character variable based on your project requirements.

Remember that you can find additional support for TinyMCE when signing up for a FREE API key , and information on the TinyMCE GitHub page .

TinyMCEConfigurationDevelopersProduct Development
byJoe Robinson

Technical and creative writer, editor, and a TinyMCE advocate. An enthusiast for teamwork, open source software projects, and baking. Can often be found puzzling over obscure history, cryptic words, and lucid writing.

Related Articles

  • How-to Use TinyMCE

    How to load and post Ajax content in TinyMCE

    by Joe Robinson in How-to Use TinyMCE
Subscribe for the latest insights served straight to your inbox every month.

Deploy TinyMCE in just 6 lines of code

Built to scale. Developed in open source. Designed to innovate.

Begin with your FREE API Key
Tiny Editor
Tiny logo
Privacy Policy - Terms of Use© 2022 Tiny Technologies Inc.TinyMCE® and Tiny® are registered trademarks of Tiny Technologies, Inc.

Products

  • TinyMCE
  • Tiny Drive
  • Customer Stories
  • Pricing