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.

3
  • See this: stackoverflow.com/a/41479077/1791913 Commented Jul 31, 2017 at 14:17
  • why you need text box? if only accepting numbers. Commented Jul 31, 2017 at 14:17
  • Why do you have to use type text? Who or what is forcing you to? Commented Jul 31, 2017 at 14:25

3 Answers 3

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;
  }
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it's works but you can prefer the directives for this issue.
Why is there a normal "return" in what should be a boolean function? What does that return?
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.

Comments

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

3 Comments

Welcome to SO! Please explain what your code does, otherwise user with the same problem wount be able to learn of your solution.
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 - arulkumarsivaraj.blogspot.com/2020/06/… Allow only numbers: arulkumarsivaraj.blogspot.com/2020/06/…
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.