0

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.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
TechnoSavvy
  • 107
  • 4
  • 18

3 Answers3

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
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