網站搜尋

javascript - 在 Angular 6 中使用正則表達式移除除數字外的字符,並僅允許單個小數點


我已經看過類似的問題,但似乎沒有任何解決方案對此有效。我有一個 Angular Material 輸入框。這個輸入框應該只接受數字和小數點。所有其他字符應在按鍵刪除時被識別並移除。

這是我的程式碼:

在 TS 檔案與 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>

請幫忙。提前感謝。

答案#1

你可以使用 keypress 事件:

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

以及 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;
   }

工作範例可以在這裡看到

答案#2

這裡是你需要的演示。簡單又容易的正則表達式。

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