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.
Asked
Active
Viewed 3,965 times
0

k0pernikus
- 60,309
- 67
- 216
- 347

TechnoSavvy
- 107
- 4
- 18
-
See this: https://stackoverflow.com/a/41479077/1791913 – FAISAL Jul 31 '17 at 14:17
-
why you need text box? if only accepting numbers. – Hareesh Jul 31 '17 at 14:17
-
Why do you have to use type text? Who or what is forcing you to? – k0pernikus Jul 31 '17 at 14:25
3 Answers
2
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;
}
}
}

Community
- 1
- 1

Murat Denizli
- 21
- 6
-
Yeah it's works but you can prefer the directives for this issue. – Can Karakoyun Jan 07 '19 at 12:25
0
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.

Devesh Jadon
- 7,004
- 4
- 22
- 27
0
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;
}

ArulKumar
- 39
- 5
-
Welcome to SO! Please explain what your code does, otherwise user with the same problem wount be able to learn of your solution. – Hille Jul 15 '20 at 13:35
-
Actually i wrote function for restrict 2-decimal values from that i derived above one. We can use same function for allow decimal values for slight modification. See below two examples u can understand. for allow only 2 decimal value - https://arulkumarsivaraj.blogspot.com/2020/06/allow-2-digit-decimal-value-from-001-to.html Allow only numbers: https://arulkumarsivaraj.blogspot.com/2020/06/allow-2-digit-decimal-value-from-001-to.html – ArulKumar Jul 15 '20 at 16:18
-
Actually written regx for allow one dot, for only number no need that so replaced with empty. //replace more than one dot inputData.replace(/[^0-9.]/g, '').replace('.', 'x') -> it will extract numbers and dots from that we replace first dot with x. .replace(/\./g, '') -> it will remove other dots .replace('x', '.') -> again replace x to Dot – ArulKumar Jul 15 '20 at 16:34