1

I am trying to remove everything except numbers, colon (:) and a new line. After having entered values with colon say 12:30, when I press enter, I am not able to submit using custom directives. So as of now, I am able to allow numbers and colon but not the enter key.

My custom directive looks something like this :

export class NumberDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initalValue.replace(/[^0-9:\n]*/g, '');
    if ( initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }

Please let me know how this can be fixed and thanks in advance.

Aravind S
  • 463
  • 2
  • 9
  • 25

1 Answers1

0

Bellow I show two approaches, one by updating the text after it is changed, the second by preventing the default behavior of specific keys. The first is more general, but for this case I prefer the second because it prevents the text from going there. The other detail is that by the piece of code you shared I don't understand why you call stopPropagation

const [txt1, txt2] = document.querySelectorAll('textarea')

txt1.addEventListener('input', () => {
  txt1.value = txt1.value.replace(/[^0-9:\n]+/g, '')
})
txt2.addEventListener('keypress', (event) => {
  if(!(/[0-9:]|Enter/i).test(event.key)){
    event.preventDefault();
  }
})
textarea { min-height: 5cm }
<textarea placeholder="Type here"></textarea>

<textarea placeholder="Type here"></textarea>
Bob
  • 13,867
  • 1
  • 5
  • 27