There is not currently a way to restrict the length of a medium-editor field. There is an open issue in the github repo discussing ways that this could be accomplished.
Browsers do not offer a maxLength property on contenteditable fields. What also makes this problematic is that these fields contain markup, so if you were to introduce a maxLength you would need to find a way to ignore the length of all the text and instead track/limit the number of "printable characters". Example:
<b>Bold and <i>italic</i></b>
The full length of this text would be 29 characters (including the tags) but you would likely want the length to be calculated as just 15 characters ("Bold and italic").
Here is a stackoverflow post suggesting ways to restrict the length of text within a contenteditable field, which is what medium-editor is using for WYSIWYG text:
Limiting Number of Characters in a ContentEditable div
At first glance, the solutions in that article aren't sufficient on their own because they either depend on jQuery (medium-editor is vanilla JS only) or the .innerText
property of elements (which is not supported in IE < 11 or Firefox < 50).
Any solution proposed which could work in IE >= 9 and not require jQuery could immediately be introduced in medium-editor as a feature to resolve issue #962
The other difficult part about implementing this is how to actually enforce the length restriction. The solutions called out in the other stackoverflow article are listening to keyup
and keydown
events, which allow you to detect when the user is typing and call event.preventDefault()
to prevent the text from being entered. This doesn't account for times when the user pastes content into the editor or if document.execCommand()
is executed (which is how built-in text formatting is handled by the browser). You could listen for the paste
event, but you will not be able to detect the content of the paste consistently across browsers without allow the paste to happen and then inspect the html.
So, you would likely have to be restricted to reacting to changes in the editor and then removing characters. This has the ugly consequence of flashing text, but it would be the only way to consistently restrict the length when things like user pasting or document.execCommand()
occur.
The input
is a great way to detect any changes to the editor (including pasting and document.execCommand()
) for all browsers except IE + Edge, which have never supported the input
event on contenteditable fields. However, MediumEditor exposes a editableInput
event which will simulate the event consistently across all browsers (I just so happened to have written that standardization, and let me tell you, it was hard to fake the input event in IE + Edge!).