简体   繁体   English

如何使输入框只接受浮动输入

[英]How to make input box accept only floating input

I have 1 common text box which is my custom component, which i am using 2 places, one is to accept integer and another is float.我有 1 个通用文本框,这是我的自定义组件,我正在使用 2 个地方,一个是接受 integer,另一个是浮动的。 if my dataType=2 , it should accept only integers which i did, but how can I make the input box which should accept only float number on keypress when dataType=3如果我的dataType=2 ,它应该只接受我所做的整数,但是当dataType=3时,我怎样才能使输入框只接受按键上的浮点数

html html

<input class="form-control"
               type="text"
               [(ngModel)]="fieldValue"
               (keypress)="checkInputType($event)" />

ts ts

checkInputType(event): boolean {
    if (this.dataType === 2) {
      const charCode = event.which ? event.which : event.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        this.alertService.error("Can't enter any character");
        return false;
      }
    }

    if (this.dataType === 3) {
      
    }
    return true;
  }

Per this SO answer , one way to do it is by validating the number is a float with regex.根据这个 SO answer ,一种方法是验证数字是带有正则表达式的浮点数。

Edit: If you want to restrict the input to only floating point numbers, you can use the pattern attribute on the input element , which validates using regex.编辑:如果您想将输入限制为仅浮点数,您可以使用input元素上的pattern属性,该属性使用正则表达式进行验证。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM