简体   繁体   中英

Regular expression to remove characters other than number and allow single decimal dot only in Angular 6

I have read similar questions and no solutions seem to be working for this. I have a Angular material input box. The input should receive only numbers and a decimal dot. All other characters should be identified and removed on keypress removal.

This is my code:

In TS file and html:

 allownumbersonly(inputVal) { inputVal = inputVal.replace(/[^0-9.]/g, '');//Modified after responses from stack overflow. this.myForm.controls['inNum'].setValue(inputVal); }
 <mat-form-field> <input id="inputNumber" matInput (keyup)="allownumbersonly($event.target.value)" placeholder="enter a number" formControlName="inNum"> </mat-form-field>

Please help. Thanks in advance.

You can use keypress event:

<input (keypress)="isNumberKey($event)"/>

and typescript:

isNumberKey(evt){
      console.log(evt.keyCode);
      let charCode = (evt.which) ? evt.which : evt.keyCode;
      if (charCode != 46 && charCode > 31 
        && (charCode < 48 || charCode > 57))
          return false;

      return true;
   }

Work example can be seen here

Here is the demo for what you need. Easy and simple regex.

 function myFunction(){ var demo = document.getElementById('demo'); demo.value = demo.value.replace(/[^0-9.]/g, ''); }
 <input type="text" id="demo" onkeyup="myFunction()">

We can use the regex in ng-pattern itself:

<input type="number" ng-model="price" name="price_field" ng-pattern="/[^0-9.]/g" required>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM