![](/img/trans.png)
[英]Javascript Regular Expression to remove any characters other than letters or space
[英]Regular expression to remove characters other than number and allow single decimal dot only in Angular 6
我讀過類似的問題,似乎沒有解決方案適用於此。 我有一個 Angular 材質輸入框。 輸入應該只接收數字和一個小數點。 在移除按鍵時應識別並移除所有其他字符。
這是我的代碼:
在 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>
請幫忙。 提前致謝。
您可以使用keypress
事件:
<input (keypress)="isNumberKey($event)"/>
和打字稿:
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;
}
這是您需要的演示。 簡單易用的正則表達式。
function myFunction(){ var demo = document.getElementById('demo'); demo.value = demo.value.replace(/[^0-9.]/g, ''); }
<input type="text" id="demo" onkeyup="myFunction()">
我們可以在 ng-pattern 本身中使用正則表達式:
<input type="number" ng-model="price" name="price_field" ng-pattern="/[^0-9.]/g" required>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.