1

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.

Darksymphony
  • 2,155
  • 30
  • 54

1 Answers1

3

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

Cristián Ormazábal
  • 1,457
  • 1
  • 9
  • 18
  • well, I did not think that I can bind also the maxlength, so thanks for this. But the problem is, I have no maxlength value, because I only know, the max bytes that DB can accept. So I can't just define maxlength as a fixed number as it may vary according to 2-bytes chars etc. Maxlength must be in chars, not bytes – Darksymphony May 14 '19 at 08:23
  • 1
    I get it. My best approach would be to set the max size of the string as the DB bytes divided by two. Hope this helps. – Cristián Ormazábal May 14 '19 at 13:38
  • yes, I think I will go this way, so in that case I can use maxlength with half size of DB bytes as you suggested (and I don't expect that user will use all characters 2-bytes) so it should be far enough. – Darksymphony May 14 '19 at 20:09