krishna
krishna

Reputation: 93

How to prevent additional characters on input field when max length reached in angular app

I am implementing a directive to stop the user from typing additional characters in the input field in my angular 6 apps. And to allow non-data input keys such as tab, del, backspace etc, and I have an if condition with event.which

export class MaxLengthDirective {

maxLength: number;

constructor(private el: ElementRef, private ngControl: NgControl) {}

@HostListener('keydown', ['$event'])
onKeyDown(event) {
 const element = this.el.nativeElement;
 if (element.value.length >= this.maxLength) {
  if (event.which !== 8 && event.which !== 9 && event.which !== 46)
    event.preventDefault();
  }
 }
}

But my if condition grows longer when I want to allow more keyboard inputs such ctrl+ C or back arrow or shift + tab etc

Is there a smarter way of handling this nondata inputs on my input control when length exceeds, so that i can still accept non data keys such as tab, del,back arrow etc

Upvotes: 1

Views: 2070

Answers (1)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

My non-pure angular proposition (allow only alphanumeric keys):

<input type="text" onkeydown="return /[a-z0-9]/i.test(event.key)" [attr.maxlength]="maxLength">

Upvotes: 1

Related Questions