Reputation: 499
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.
Upvotes: 2
Views: 1833
Reputation: 304
We can use the regex in ng-pattern itself:
<input type="number" ng-model="price" name="price_field" ng-pattern="/[^0-9.]/g" required>
Upvotes: 1
Reputation: 7979
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()">
Upvotes: 2
Reputation: 38209
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;
}
Upvotes: 3