I am creating an app in ionic4, I have a functionality where user can enter the only integer number (0-9), so I want to restrict any other character i.e alphabets, dot, plus everything.
I tried to restrict is using the following directive
@HostListener('input', ['$event']) onInputChange(event) {
this.inputElement = this._el.nativeElement.getElementsByTagName('input')[0];
const initalValue = this.inputElement.value;
this.inputElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this.inputElement.value) {
event.stopPropagation();
}
}
It is updating ngModel correctly but still, an invalid character is visible in the input field.
I tried another option as 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, '');
}
With above its printing value in HTML correct without invalid character, but its showing invalid character in input.
If I enter 5+ in input, the value in ngModel shows 5 but input field showing 5+
When I type 5++ and then type 5 again, input field shows 55 now.
How can I restrict input to accept only integer values [0-9]