简体   繁体   English

如何使用TypeScript只允许html输入类型文本中的数字?

[英]How to allow only numbers in html input type text using TypeScript?

I have a HTML textbox.我有一个 HTML 文本框。 How to allow only numbers in it on keypress event?如何在按键事件中只允许数字? There is a type=number however I have use type text.有一个type=number但是我使用了类型文本。

You can use "keypress" event in your text input.您可以在文本输入中使用“keypress”事件。 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;
  }
}
}

您可以在组件中使用响应式表单,并且为了仅允许输入字段中的数字,您可以使用Validators.pattern("^\\\\d+$")像 minlength,在此表单中处理所需的验证。

HTML: HTML:

<input type="text" (input)="onTextboxChangeValidate($event)">

TS file include below function TS 文件包括以下功能

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 只允许在带有 Angular 的文本输入中输入数字 - Allow only numbers in a text input with Angular Angular 2/4 需要一个 Typescript 正则表达式来只允许将数字输入到输入文本框中 - Angular 2/4 need a Typescript regex to only allow numbers to be entered into input textbox 允许在on之前和之后使用十进制数和限制数<input type="“text”"> - Allow decimal numbers and limit numbers before and after on <input type=“text”> 当输入类型为文本时,如何使输入字段只接受数字? - how can I make an input field only accept numbers when the input type is text? 如何在打字稿中动态创建输入文字 - How to create input type text dynamically in typescript 如何在我的输入中只允许数字和特殊字符? - How do I allow only numbers and special characters in my input? 如何使用指令仅允许在输入类型“ tel”中输入数字(0-9)-Ionic 3 Angular 5 - How to only allow digits(0-9) to be entered in input type 'tel' using directive - Ionic 3 Angular 5 如何允许<input type="“file”">只接受.jpeg 和.jpg 文件? - How to allow <input type=“file”> to accept only .jpeg and .jpg files? 如何允许用户覆盖输入类型数字中的数字(当已经有两个数字时)? - How can I allow users to overwrite the numbers in the input type number (when there are already two numbers)? 如何使我的输入文本字段只允许字母正确? - How to make my input text field only allow letters properly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM