Search code examples
htmlinputclipboardpastemaxlength

HTML INPUT element with maxLength loses text when paste from clipboard


Could not find anything for what I consider a fundamental problem:

When you paste characters from the clipboard into an HTML element with maxLength attribute set, it appears that only a piece of the copied text is inserted when the whole text does not fit into maxLength.

Tested with Chrome 89.0.4389.90 (Official Build) and Firefox 78.8.0esr, same behavior.

Is there some specification or standard about that behavior? Any discussion that already took place about this?

Sorry if it's a stupid question, maybe am missing something here.

But IMO this behavior is NOT a good thing: I can lead to DATA LOSS! Don't agree?

Imagine you copy/paste some UUID, SHA-1 checksum, parts of code, or text for a law where each word matters: Pieces can get silently lost!? Not even a warning telling you that your reached maxLength?

When typing individual chars from the keyboard, it's different: You get immediate visual feedback so your can't miss the limit.

OK, usually text input fields may not use maxLength... But if you have an SQL database behind this where columns have a fixed length like VARCHAR(500), you want to limit to 500 chars (assuming the SQL DB uses Char Length Semantics)

So I think it should paste either all or nothing, but not pieces of text.

Is there an attribute/CSS style to control this in the element?

Best regards, Seb


Solution

  • Unfortunately, the one you face is the expected work of maxlength attribute. It is smart enough to capture that part that is less than or equal to the maxlength. If you do not want this working, you have to manually handle it through JavaScript, and it is pretty straightforward. Here's a quick example:

    function checkLength() {
      var input = document.getElementById("value")
      if (input.value.length >= 5) // 5 is your maxlength
         input.value='';
    }
    <input type="text" id="value" onInput="checkLength();"/>

    The above code clears the input field when the value is more than the specified length, and no maxlength attribute is needed here. If you want this spec only for paste events, you can use onpaste attribute instead of oninput.