Reputation: 107
I have a HTML textbox. How to allow only numbers in it on keypress event?
There is a type=number
however I have use type text.
Upvotes: 0
Views: 4701
Reputation: 59
HTML:
<input type="text" (input)="onTextboxChangeValidate($event)">
TS file include below function
onTextboxChangeValidate(event: Event)
{
var inputData = (<HTMLInputElement>event.target).value;
//replace more than one dot
var extractedFte = inputData.replace(/[^0-9.]/g, '').replace('.', '')
.replace(/\./g, '').replace('x', '.');
//Extract nuber Values
extractedFte = extractedFte.replace(/^(\d+)\d*$/, "$1");
//Reasign to same control
(<HTMLInputElement>event.target).value = extractedFte;
}
Upvotes: 0
Reputation: 21
You can use "keypress" event in your text input. You can use this function.
<input id="example" type="text" [(ngModel)]="example" (keypress)="OnlyNumbers($event)" />
public OnlyNumbers($event) {
let regex: RegExp = new RegExp(/^[0-9]{1,}$/g);
let specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowRight','ArrowLeft'];enter code here
if (specialKeys.indexOf($event.key) !== -1) {
return;
} else {
if (regex.test($event.key)) {
return true;
} else {
return false;
}
}
}
Upvotes: 2
Reputation: 7474
You can use Reactive Forms in your component and for allowing only numbers in input field you can use Validators.pattern("^\\d+$")
like minlength, required validations are handled in this form.
Upvotes: 0