I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not completely restricted these invalid characters.
@HostListener('input', ['$event']) onInputChange(event) {
this.inputElement = this._el.nativeElement.getElementsByTagName('input')[0];
const initialValue = this.inputElement.value;
this.inputElement.value = initialValue.replace(/[^0-9]*/g, '');
if (initialValue !== this.inputElement.value) {
event.stopPropagation();
}
}
While the above method is correctly updating ngModel, it still displays invalid characters in the input field.
Another approach I attempted includes the following:
html
<ion-input type="text" placeholder="Enter number"
[(ngModel)]="userCount"
name="userCount"
(ionInput)="countChange($event)">
</ion-input>
Usercount: {{userCount}}
Typescript
countChange(event) {
event.target.value = event.target.value.replace(/[^0-9]*/g, '');
}
Although the second method accurately displays the value in HTML without invalid characters, they are still visible in the input field.
For example, if "5+" is entered in the input, the ngModel value displays "5" but the input field shows "5+". Additionally, typing "5++" and then "5" changes the input field to display "55".
I am seeking a solution that will strictly restrict users from entering anything other than integer values within the range of [0-9].