简体   繁体   English

如何使输入字段仅通过AngularJS接受INTEGERS

[英]How can I make input field accept INTEGERS only with AngularJS

How can I prevent typing anything except digits (integers) into an input field with angularJS 如何防止使用angularJS在输入字段中键入除数字(整数)以外的任何内容

type="number" allows floating point numbers type =“ number”允许浮点数

I also tried several regexes with ng-pattern, but those floating points were still allowed, although I explicitly specified digits only. 我还尝试了几种使用ng-pattern的正则表达式,但是尽管我仅明确指定了数字,但仍允许使用这些浮点数。

I'm fiddling with watchers at the moment, but can't make them work properly, at least not yet. 我目前正在和观察者摆弄,但不能使他们正常工作,至少目前还不能。 I'm thinking of writing keydown event handlers for these fields, but still hoping there's better way. 我正在考虑为这些字段编写keydown事件处理程序,但仍然希望有更好的方法。

This will make the input to a stepMitchMatch if entering something like 1.4 如果输入类似1.4的内容,这将使输入到stepMitchMatch

Regex pattern is unnecessary as you can do it with common attributes 正则表达式模式是不必要的,因为您可以使用通用属性来完成

 :invalid{ background: red } :valid{ background: lime } 
 <input type="number" step="1"> 

If you need to overdo it, then use angular-ui/mask with 9?9?9?9?9?9?9?9?9?9? 如果需要覆盖,请使用angular-ui / mask和9?9?9?9?9?9?9?9?9?9? as the masked value 作为屏蔽值

Try this: 尝试这个:

<input type="number" step="1" ng-pattern="^[0-9]+$">

The regex will fail anything other then a round integer and the step will automatically make the up/down arrows add/subtract 1 正则表达式将使除舍入整数以外的所有内容失败,并且该步骤将自动使向上/向下箭头加/减1

You can use a regex string within ng-pattern to validate your input. 您可以在ng-pattern中使用正则表达式字符串来验证输入。

ng-pattern="^-?[0-9]*$"

If you want to only allow positive numbers, remove the "-?" 如果只允许使用正数,请删除“-”。

You can also test out your patterns at the bottom of this page: https://docs.angularjs.org/api/ng/directive/ngPattern 您还可以在此页面底部测试模式: https : //docs.angularjs.org/api/ng/directive/ngPattern

Edit : 编辑

I missed that you want to prevent users from typing invalid characters. 我想念您要防止用户键入无效字符。 There's an solution over here: https://stackoverflow.com/a/28975658/6440513 that answers your question, and you can use the regex pattern within the directive provided there. 这里有一个解决方案: https : //stackoverflow.com/a/28975658/6440513可以回答您的问题,您可以在此处提供的指令中使用regex模式。

You can use ng-pattern to resolve this 您可以使用ng-pattern解决此问题

<input type="number" ng-pattern="/^[0-9]{1,7}$/">

This will let you enter numbers in the range of 0-9999999 这样您就可以输入0-9999999范围内的数字

Create a directive may be? 创建指令可能是?

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='number' step='1' />",
    replace: true,
    link: function(scope, e, attrs) {    
      e.bind("keydown", function(e) {

        if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
          e.preventDefault();
        }
      });
    }
  };
});

then use it in your app like so 然后像这样在您的应用程序中使用它

<div ng-app="myApp">
 <my-number><my-number>
</div>

You can garnish it further to allow bindings, and special keys 您可以进一步修饰它以允许绑定和特殊键

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='text' ng-model='model' />",
    replace: true,
    scope: {model : "="},
    link: function(scope, e, attrs) {

      e.bind("keydown", function(e) {
        // Special request from @endless for all these keys to be exempted
        //
        if (e.ctrlKey || e.altKey || e.keyCode >= 0 && e.keyCode <= 31 || e.keyCode >= 33 && e.keyCode <= 40 || e.keyCode==46) {
          return;
        }
        else if (!(e.ctrlKey || (e.keyCode >= 48 && e.keyCode <= 57 && !e.shiftKey))) {
          e.preventDefault();
        }
      }).bind("change", function() {
         var e = angular.element(this);
         if (isNaN(parseInt(e.val())) || e.val().indexOf(".") >= 0) {
            alert("incorrect number value entered");
            e.val("");
         }
      });
    }
  };
});

Here is a working plunkr example 这是一个工作的例子

Here is another fork of the above that allows all the special keys 这是上面的另一个分支,它允许所有特殊键

Here is more info on directives 这是有关指令的更多信息

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

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