ANewGuyInTown
ANewGuyInTown

Reputation: 6447

How to prevent user from pasting incorrect value in a text box in angular 2?

I'm trying to create a control that that let user enter hh:mm in a text box. However, I'm not able to get it working correctly when user tries to paste the invalid text.

Though the users are not able to type non alpha numeric character. They are still able to paste it.

This is my host event that prevents user from typing any character other than allowed characters

@HostListener("keydown", ["$event"])
@HostListener("keyup", ["$event"])
onKeyDown(event: any) {
  let allowedCharacters = `^[0-9-:]*$`;
  const e = event as KeyboardEvent;
    if ([8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
        //Ctrl+A
        (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
        //Ctrl+C
        (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
        //Ctrl+V
        (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
        //Ctrl+X
        (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
        //home, end, left, right
        (e.keyCode >= 35 && e.keyCode < 39)) {
        return;
    }
    if (!String(e.key).match(allowedCharacters)) {
      event.preventDefault();
    }
}

This is my ngModelChange event

 onModelChange(value: any): void {
   this.myTextBoxValue= value;
}

And this is my textbox:

<input type="text" [ngModel] = "myTextBoxValue" (ngModelChange)="onModelChange($event)" 

Upvotes: 1

Views: 2499

Answers (3)

anilam
anilam

Reputation: 892

You can do this so user is not able to paste values in the textbox.

<input (paste)="false" />

Upvotes: 0

Paka
Paka

Reputation: 1053

Trigger a paste event

<input type="text" [ngModel] = "myTextBoxValue" (paste)="onPaste($event)" (ngModelChange)="onModelChange($event)" 

Component:

onPaste(e: any) { e.preventDefault()}

Upvotes: 3

Emad Dehnavi
Emad Dehnavi

Reputation: 3441

Try this in your keydown method :

onKeyDown(event: any) {
   const e = event as KeyboardEvent;
   var charCode = e.keyCode;
   if (charCode > 31 && (charCode < 48 || charCode > 58 )) {
      return false;
   }
      return true;
}

This only allow to enter numbers and : char. hope it can help you.

Upvotes: 0

Related Questions