仅允许数值输入输入字段

时间:2017-09-25 11:38:17

标签: javascript angularjs regex

我编写了下面的指令,它只允许在输入字段中输入数值。除了允许输入字母数字之外,例如如果我复制了“abc123”并在输入字段中粘贴它然后它接受数字并忽略不应该是这种情况的字母表。在这种情况下,它不应该允许在输入字段中粘贴任何东西。请帮忙。

package main

import (
    "fmt"
    "log"
    "net/http"
    "crudgo/backend/home"
    "github.com/gorilla/mux"
  )

func main() {
     http.FileServer(http.Dir("./public/p/dist"))
     log.Println("Listening...")

     router := mux.NewRouter();

     home.HomeRoute(router)

     router.PathPrefix("/{_:.*}").Handler(http.FileServer(http.Dir("./public/p/dist")))

     http.ListenAndServe("localhost:3000", router)
}

4 个答案:

答案 0 :(得分:1)

$parsers

<input type="text" ng-model="test" format="number" />

JS

app.directive('format', ['$filter', '$window', function($filter, $window) {
  return {
    require: '?ngModel',
    link: function(scope, elem, attrs, ctrl) {
      if (!ctrl) return;

      scope.vKey = 86;
      scope.ctrlVDown = false;
      angular.element($window).bind("keydown", function($event) {
        console.log($event.keyCode);
        if ($event.keyCode == scope.vKey) {
          scope.ctrlVDown = true;
        } else {
          scope.ctrlVDown = false;
        }
      });


      ctrl.$parsers.unshift(function(viewValue) {
        var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');

        console.log(scope.ctrlVDown);

        if (scope.ctrlVDown && plainNumber.length !== viewValue.length) {
          elem.val('');
          return '';
        } else {
          elem.val(plainNumber);
          return plainNumber;
        }
      });
    }
  };
}]);

Demo Fiddle

答案 1 :(得分:1)

下面是一个简单的指令,它只允许您在输入字段中输入数字。

链接到输入字段时:

<input type="text" ng-model="test" valid-number>

它在输入字段上绑定一个keydown事件,用于检查已按下的键。键盘上的每个键都有一个全局编号。例如: enter 已分配数字 13

A complete list of key codes

当您按键盘上的某个键时,它与var keyCode

中列出的键码相匹配
var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];

然后我们阻止该行动的执行。

(function () {

  angular.module("app", [])
  
  .directive("validNumber", function () {
        return {
            restrict: "EA",
            require: "?ngModel",
            link: function (scope, element, attrs, ngModel) {
                if (!ngModel) return;
                var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
                element.bind("keydown", function (event) {
                    if ($.inArray(event.which, keyCode) === -1) {
                        scope.$apply(function () {
                            scope.$eval(attrs.validNumber);
                            event.preventDefault();
                        });
                        event.preventDefault();
                    }
                });
            }
        };
    });

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app">
  <input type="text" ng-model="test" valid-number="" name="test">
</div>

更新

根据您对其他贴子的评论。您可以使用.replace()函数替换除数字之外的所有内容。

即使您使用无效字符复制并粘贴有效数字,它也会替换无效字符。

我允许用户写一个点.,因为5.2是一个有效数字。但如果你不想这样,你可以用{/ 1>替换regex

value.replace(/[^0-9]/g, "");

<强>样本

(function () {

  angular.module("app", [])
  
  .directive("validNumber", function () {
        return {
            restrict: "EA",
            require: "?ngModel",
            link: function (scope, element, attrs, ngModel) {
                if (!ngModel) return;

                element.bind("keypress keyup", function (event) {
                    var value = element.val();
                    value = value.replace(/[^0-9.]/g, "");
                    
                    element.val(value);
                });
            }
        };
    });

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app">
  <input type="text" ng-model="test" valid-number="" name="test">
</div>

答案 2 :(得分:1)

这可能有帮助

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button 
{   
    -webkit-appearance: none;
    margin: 0; /* some part are still there even though it is hidden */
}
<div ng-app="app">
  <input type="number" >
</div>

如果您对键'e'感到不舒服,请使用以下

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.myFunc = function (event) {    
    if (event.keyCode < 48 || event.keyCode > 57)
    {
        event.preventDefault();
    }
};
});
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button 
{   
    -webkit-appearance: none;
    margin: 0; /* some part are still there even though it is hidden */
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-keypress="myFunc($event)">
</div>

答案 3 :(得分:0)

您是否尝试将输入类型设置为数字

<input type="number" />

即使用户使用粘贴

,这也会自动删除所有字母字符