Skip to content

Angular 2/4 need a Typescript regex to only allow numbers to be entered into input textbox

In my Angular 4 application I have this input box in which I ONLY want numbers… 0-9 to be entered.. otherwise I want it to clear out onkeyup


<input type="number" (keyup)="numbersOnly($event)"  placeholder="0000000000" formControlName="phone" maxlength="10"/>

Above works to call this function in the component but it is not working to prevent letters.

numbersOnly(val) {
    let y = this.trackerForm.controls['phone'].value
    y.value = y.value.replace(/[^0-9.-]/g, '');

    console.log('y', y);

  1. Is .value the wrong approach?
  2. Should I be using event preventdefault?

The console log for ‘y’ shows correctly.

What do I need to do?



Since you are using ReactiveForm, you should understand that FormConrtol’s value only has a getter.

If you want to change formControl’s value, use patchValue or setValue.

let y = this.trackerForm.controls['phone'];
this.trackerForm.controls['phone'].patchValue(y.value.replace(/[^0-9.-]/g, ''));
// OR
this.trackerForm.controls['phone'].setValue(y.value.replace(/[^0-9.-]/g, ''));

Refer demo.