繁体   English   中英

angularjs:只允许将数字输入文本框

[英]angularjs: allows only numbers to be typed into a text box

在angularjs有任何可用的功能,只允许数字被输入到一个文本框

此代码显示了如何防止输入非数字符号的示例。

angular.module('app').
  directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue == undefined) return '';
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
});

HTML

 <input type="text" name="number" only-digits>

//输入123

  .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
});

//键入:123或123.45

 .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits.split('.').length > 2) {
              digits = digits.substring(0, digits.length - 1);
            }

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
 });

我只是在指令中使用ng-keypress来输入。

HTML:

<input type="text" ng-keypress="filterValue($event)"/>

JS:

$scope.filterValue = function($event){
        if(isNaN(String.fromCharCode($event.keyCode))){
            $event.preventDefault();
        }
};

这个功能正是您所需要的。 http://docs.angularjs.org/api/ng.directive:input.number

编辑:

您可以将jquery插件包装到指令中。 我在这里创建了一个例子: http//jsfiddle.net/anazimok/jTJCF/

HTML:

<div ng-app="myApp">
    <div>
        <input type="text" min="0" max="99" number-mask="" ng-model="message">
            <button ng-click="handleClick()">Broadcast</button>
    </div>

</div>

CSS:

.ng-invalid {
    border: 1px solid red;
}

JS:

// declare a module
var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

这是最简单,最快速的方法,仅允许数字输入。

<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>

谢谢

以Anton的答案为基础 -

angular.module("app").directive("onlyDigits", function ()
{
    return {
        restrict: 'EA',
        require: '?ngModel',
        scope:{
            allowDecimal: '@',
            allowNegative: '@',
            minNum: '@',
            maxNum: '@'
        },

        link: function (scope, element, attrs, ngModel)
        {
            if (!ngModel) return;
            ngModel.$parsers.unshift(function (inputValue)
            {
                var decimalFound = false;
                var digits = inputValue.split('').filter(function (s,i)
                {
                    var b = (!isNaN(s) && s != ' ');
                    if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
                    {
                        if (s == "." && decimalFound == false)
                        {
                            decimalFound = true;
                            b = true;
                        }
                    }
                    if (!b && attrs.allowNegative && attrs.allowNegative == "true")
                    {
                        b = (s == '-' && i == 0);
                    }

                    return b;
                }).join('');
                if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
                {
                    digits = attrs.maxNum;
                }
                if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
                {
                    digits = attrs.minNum;
                }
                ngModel.$viewValue = digits;
                ngModel.$render();

                return digits;
            });
        }
    };
});

我的解决方案接受复制和粘贴并保存插入符号的位置。 它用于产品成本,因此仅允许正十进制值。 可以很容易地重构,允许负数或只是整数位。

angular
        .module("client")
        .directive("onlyNumber", function () {
            return {
                restrict: "A",
                link: function (scope, element, attr) {
                    element.bind('input', function () {
                        var position = this.selectionStart - 1;

                        //remove all but number and .
                        var fixed = this.value.replace(/[^0-9\.]/g, '');  
                        if (fixed.charAt(0) === '.')                  //can't start with .
                            fixed = fixed.slice(1);

                        var pos = fixed.indexOf(".") + 1;
                        if (pos >= 0)               //avoid more than one .
                            fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');  

                        if (this.value !== fixed) {
                            this.value = fixed;
                            this.selectionStart = position;
                            this.selectionEnd = position;
                        }
                    });
                }
            };
        });

放在html页面上:

<input type="text" class="form-control" only-number ng-model="vm.cost" />

这是适合我的方法。 它基于samnau anwser,但允许使用ENTER提交表单,使用UPDOWN箭头增加和减少数字,使用DELBACKSPACELEFTRIGHT ,并使用TAB导航到字段。 请注意,它适用于正整数,如金额。

HTML:

<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >

ANGULARJS:

$scope.onlyNumbers = function(event){   
    var keys={
        'up': 38,'right':39,'down':40,'left':37,
        'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
        '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    };
    for(var index in keys) {
        if (!keys.hasOwnProperty(index)) continue;
        if (event.charCode==keys[index]||event.keyCode==keys[index]) {
            return; //default event
        }
    }   
    event.preventDefault();
};

基于djsiz解决方案,包含在指令中。 注意:它不会处理数字,但可以轻松更新

angular
        .module("app")
        .directive("mwInputRestrict", [
            function () {
                return {
                    restrict: "A",
                    link: function (scope, element, attrs) {
                        element.on("keypress", function (event) {
                            if (attrs.mwInputRestrict === "onlynumbers") {
                                // allow only digits to be entered, or backspace and delete keys to be pressed
                                return (event.charCode >= 48 && event.charCode <= 57) ||
                                       (event.keyCode === 8 || event.keyCode === 46);
                            }
                            return true;
                        });
                    }
                }
            }
        ]);

HTML

 <input type="text"
        class="form-control"
        id="inputHeight"
        name="inputHeight"
        placeholder="Height"
        mw-input-restrict="onlynumbers"
        ng-model="ctbtVm.dto.height">

只需使用HTML5

<input type="number" min="0"/>

你可以查看https://github.com/rajesh38/ng-only-number

  1. 它在输入时将输入限制为文本框中的数字和小数点。
  2. 您可以限制小数点前后允许的位数
  3. 如果从文本框中删除小数点,它也会修剪小数点后的数字,例如,如果您已经放入123.45然后删除小数点,它也将删除小数点后面的尾随数字并使其成为123。

您可以这样做:使用带有RegExp“ / ^ [0-9] + $ / ”的ng-pattern ,这意味着只有整数有效。

<form novalidate name="form">
    <input type="text" data-ng-model="age" id="age" name="age" ng-pattern="/^[0-9]+$/">
    <span ng-show="form.age.$error.pattern">The value is not a valid integer</span>
</form>

此解决方案只接受数字''。' 和' - '

这也限制了文本框中的空格条目。 我曾使用该指令来实现同样的目标。

请在下面的工作示例中找到解决方案。

http://jsfiddle.net/vfsHX/2697/

HTML:

<form ng-app="myapp" name="myform" novalidate> 
<div ng-controller="Ctrl">
<input name="number" is-number ng-model="wks.number">
<span ng-show="!wks.validity">Value is invalid</span>
</div>

JS:

var $scope;
var app = angular.module('myapp', []);

app.controller('Ctrl', function($scope) {
    $scope.wks =  {number: 1, validity: true}
});

app.directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {   
        element.bind("keydown keypress", function (event) {
          if(event.which === 32) {
            event.returnValue = false;
            return false;
          }
       }); 
            scope.$watch(attrs.ngModel, function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    //scope.wks.number = oldValue;
                    ngModel.$setViewValue(oldValue);
                                    ngModel.$render();
                }
            });

        }
    };
});

这很简单易懂。 只需复制粘贴此代码,您的问题就会得到解决。对于更多条件,只需更改模式中的值即可。您的工作将完成。

<input type="text"  pattern="[0-9]{0,}" oninvalid="this.setCustomValidity('Please enter only numeric value. Special character are not allowed.')" oninput="setCustomValidity('')">
<input type="phone" numbers-only >

如果你只想要数字,你可以使用这种方式:)

这是演示点击

我有一个类似的问题,最终挂钩和事件

ng-change="changeCount()" 

然后:

self.changeCount = function () {
      if (!self.info.itemcount) {
        self.info.itemcount = 1;
      }
 };

因此,如果插入了无效的号码,则用户默认为1。

我在这里激怒了jQuery

.directive('numbersCommaOnly', function(){
   return {
     require: 'ngModel',
     link: function (scope, element, attrs, ngModel) {

        element.on('keydown', function(event) {                  
            // Allow: backspace, delete, tab, escape, enter and .
            var array2 = [46, 8, 9, 27, 13, 110, 190]
            if (array2.indexOf(event.which) !== -1 ||
                 // Allow: Ctrl+A
                (event.which == 65 && event.ctrlKey === true) ||
                 // Allow: Ctrl+C
                (event.which == 67 && event.ctrlKey === true) ||
                 // Allow: Ctrl+X
                (event.which == 88 && event.ctrlKey === true) ||
                 // Allow: home, end, left, right
                (event.which >= 35 && event.which <= 39)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
                event.preventDefault();
            }
         });

     }
   };
})
 <input type="text" ng-keypress="checkNumeric($event)"/>
 //inside controller
 $scope.dot = false
 $scope.checkNumeric = function($event){
 if(String.fromCharCode($event.keyCode) == "." && !$scope.dot){
    $scope.dot = true
 }
 else if( isNaN(String.fromCharCode($event.keyCode))){
   $event.preventDefault();
 }

我知道这是一个很老的帖子,但是My Mai的答案的改编对我很有帮助 ......

angular.module("app").directive("numbersOnly", function() {
  return {
    require: "ngModel",
    restrict: "A",
    link: function(scope, element, attr, ctrl) {
        function inputValue(val) {
            if (val) {
                //transform val to a string so replace works
                var myVal = val.toString();

                //replace any non numeric characters with nothing
                var digits = myVal.replace(/\D/g, "");

                //if anything needs replacing - do it!
                if (digits !== myVal) {
                    ctrl.$setViewValue(digits);
                    ctrl.$render();
                }
                return parseFloat(digits);
            }
            return undefined;
        }
        ctrl.$parsers.push(inputValue);
    }
  };
});

我做过

.js文件

$scope.numberOnly="(^[0-9]+$)";

html的

<input type="text" name="rollNo" ng-model="stud.rollNo" ng-pattern="numberOnly" ng-maxlength="10" maxlength="10" md-maxlength="10" ng-required="true" >

这个答案可以简化和优化Leopoldo的答案

在每个keydown上从你的输入触发一个函数,如下所示:

<input type="text" ng-keydown="onlyNumbers($event);"/>

您可以在控制器中以这种方式描述该功能

$scope.onlyNumbers = function(event){    
    // 'up': 38,'right':39,'down':40,'left':37,
    // 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
    // '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
                 46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
                 54:true,55:true,56:true,57:true };

    // if the pressed key is not listed, do not perform any action
    if(!keys[event.keyCode]) { event.preventDefault(); }
}

如果你使用Angular 2+,你可以用这种方式调用同一个函数:

<input type="text" (keydown)="onlyNumbers($event);"/>

你的Angular 2+函数应该是这样的:

onlyNumbers(event) { // the logic here }

使用ng-only-number允许数字,例如:

<input type="text" ng-only-number data-max-length=5>
 <input
    onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||                         
    event.charCode == 0 || event.charCode == 46">

暂无
暂无

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

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