Darksymphony
Darksymphony

Reputation: 2683

javascript onkeypress limit characters when pasting

I've a textarea with keydown.trigger in Aurelia:

<textarea name="description" keydown.trigger="handleKeypress($event, $event.target.value)" 
value.bind="desc" ></textarea>

In .js file then I have this code:

handleKeypress(event,newValue) { 
  let max = 3413;
  let valueSize = new Blob([newValue]).size; 
  if (event.charCode >= 48 && event.charCode <= 57 || event.key === "Backspace") {
    return true;
  }
  else {
    event.onpaste = function(e){
        e.clipboardData.getData('text/plain').slice(0, max);
};
    if (valueSize>= max) {return false;} 
  }
  return true;
}

So this shouldn't allow more characters than 3413 bytes in textarea as in DB I have limits in bytes, so I can't use simple maxlength here.

This code works fine, it doesn't allow to enter more characters. It also doesn't allow pasting text with CTRL+V but only if the limit is reached.

The problem is, when the limit is NOT reached yet and someone pastes a long text via CTRL+V or right mouse click - paste. Then the content is pasted and it is over limit in textarea.

I want to achieve that textarea doesn't show more chars than the limit

UPDATE: I also tried to use the mentioned solution from another thread via e.clipboardData.getData('text/plain').slice(0, max);

but this does nothing in my case.

Upvotes: 1

Views: 679

Answers (1)

what's the problem with using maxlength?

I tried it and it works for me:

<template>
     <textarea name="description" maxlength.bind="max" value.bind="desc"></textarea>
</template>

And in the viewmodel:

export class Test {
  max = 3;
}

I tested this in codesandbox and works fine. See https://codesandbox.io/embed/4zy4k5r3k7

Upvotes: 3

Related Questions