DEV Community

Dhanush
Dhanush

Posted on

Answer: Angular - Input Field To Accept Only Numbers

<input type="text" (keypress)="keyPress($event)">


  keyPress(event: any) {
    const pattern = /[0-9\+\-\ ]/;

    let inputChar = String.fromCharCode(event.charCode);
    if (event.keyCode != 8 && !pattern.test(inputChar)) {
      event.preventDefault();
    }
  }

Top comments (0)