[翻译]  Prevent the letter 'e' and dots from being typed in an input number

[CHINESE]  防止在输入数字中输入字母'e'和点


I have a simple input number like this:

我有一个简单的输入数字,如下所示:

<input type="number"/>

When trying to input anything other than a number or the letter "e", it doesn't work, but when I type the letter "e" it works.

当试图输入除数字或字母“e”以外的任何内容时,它不起作用,但是当我输入字母“e”时它起作用。

I checked w3.org specs, and it states clearly that floating numbers can be typed using the normal notation (ex : 10.2) or the scientific notation (ex : 1e2).

我检查了w3.org规范,并清楚地说明浮动数字可以使用常规符号(例如10.2)或科学符号(例如:1e2)键入。

So my question is : Is there a way to prevent the user from typing e letters and dots. Said in another way : Is there a way to make the input number accept ONLY INTEGER NUMBERS ?

所以我的问题是:有没有办法防止用户输入电子信件和点。换句话说:有没有办法让输入数字只接受整数?

I have the idea of doing that with an Angular directive that I will input as an attribute to my input number, but I really don't know how to make that work.

我有一个Angular指令的想法,我将输入作为输入数字的属性,但我真的不知道如何使这项工作。

EDIT : What I would like to do is to simulate the same behaviour that we have now when trying to type any other letter in the alphabet other than "e", or ".". What I want to say is that I do not want to see the letter appearing in the input (Like it is the case now).

编辑:我想要做的是模拟我们现在尝试键入除“e”或“。”以外的字母表中的任何其他字母时所具有的相同行为。我想说的是,我不想看到输入中出现的字母(就像现在的情况一样)。

2 个解决方案

#1


9  

You are correct that it should be done with a directive. Simply create a directive and attach it to the input. This directive should listen for keypress and/or keydown events. Possibly paste events as well. If the char entered is an 'e' or dot -- call event.preventDefault();

你应该用指令完成它是正确的。只需创建一个指令并将其附加到输入。该指令应该监听keypress和/或keydown事件。也可能粘贴事件。如果输入的字符是'e'或点 - 调用event.preventDefault();

angular.module('app', [])
  .directive('yrInteger', yrInteger);

function yrInteger() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
    
      element.on('keypress', function(event) {

        if ( !isIntegerChar() ) 
          event.preventDefault();
        
        function isIntegerChar() {
          return /[0-9]|-/.test(
            String.fromCharCode(event.which))
        }

      })       
    
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <input 
         type="number" 
         yr-integer
         />
</div>

#2


0  

You can simply use ng-pattern on your input

您只需在输入中使用ng-pattern即可

Controller

调节器

$scope.onlyDigits= /^\d+$/;

HTML

HTML

<input ng-pattern="onlyDigits" type="number" />

This pattern use \d which is for any numeric value

此模式使用\ d,它适用于任何数值


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号