简体   繁体   English

角度 7 中的文本框只允许十进制值

[英]Allow only decimal value to the textbox in angular 7

In Angular 7, how can I mask an input field (textbox) such that it accepts only decimal value like (8.15 or 15.25) ?在 Angular 7 中,如何屏蔽输入字段(文本框),使其只接受十进制值,如 (8.15 或 15.25) ?

I have the following HTML input:我有以下 HTML 输入:

<input type="text" name="amount" id="amount" pattern="[0-9]+(\.[0-9][0-9]?)?" (keypress)="numbersOnly($event)">

i have following function numbersOnly which allow only decimal numbers but it should not allow to enter decimal point(.) more than one time like below.我有以下函数 numbersOnly ,它只允许十进制数字,但不允许输入小数点(。)超过一次,如下所示。

8.155454 or 8.65.24 8.155454 或 8.65.24

it should allow only 1 decimal points after number like below.它应该只允许在数字后有 1 个小数点,如下所示。

8.15 or 80.45 or 555.14 8.15 或 80.45 或 555.14

below is my function that accept only decimal value.下面是我只接受十进制值的函数。

 numbersOnly(event: any) {
    let charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 46 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;
    return true;
  }

You can use the keypress event to capture the input values and check in the event handler that there is only one decimal point.您可以使用 keypress 事件来捕获输入值并在事件处理程序中检查只有一个小数点。

I've done this by adding onkeypress="return slideNumber_keyFilter( event );"我通过添加onkeypress="return slideNumber_keyFilter( event );"来完成此操作to my input element and then used this function:到我的输入元素,然后使用此功能:

      <script>
        function slideNumber_keyFilter( event ) {
          return ( ( event.charCode >= 48 ) && ( event.charCode <= 57 ) );
        }
      </script>

Which in my case didn't allow for any periods, but you can simply replace the code that check the input and keep track if a period is entered, and disallow another.在我的情况下不允许有任何句点,但您可以简单地替换检查输入的代码并跟踪是否输入了一个句点,并禁止另一个。

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

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