限制用户在输入框中仅允许10位数字

时间:2017-04-08 06:44:47

标签: angularjs

我只想限制用户在手机号码字段中只输入10位数字。 我试过这段代码

 app.directive('allowOnlyNumbers', function () {  
        return {  
            restrict: 'A',  
            link: function (scope, elm, attrs, ctrl) {  
                elm.on('keydown', function (event) {  
                    if (event.which == 64 || event.which == 16) {  
                        // to allow numbers  
                        return false;  
                    } else if (event.which >= 48 && event.which <= 57) {  
                        // to allow numbers  
                        return true;  
                    } else if (event.which >= 96 && event.which <= 105) {  
                        // to allow numpad number  
                        return true;  
                    } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {  
                        // to allow backspace, enter, escape, arrows  
                        return true;  
                    } else {  
                        event.preventDefault();  
                        // to stop others  
                        return false;  
                    }  
                });  
            }  
        }  
    }); 

此代码允许用户输入数字,但它占用的数字超过10位。 谁能告诉我如何限制只有10位数?

任何帮助将不胜感激。 提前谢谢....

2 个答案:

答案 0 :(得分:3)

您也可以尝试使用ng-pattern

<input type="text" class="form-control" ng-model="sample"
       ng-pattern="/^[0-9]{10}$/">

这将需要正好10位数字,而不需要其他任何内容,以便验证通过。如果您需要最多10个数字,但数字少于此数字也可以接受,那么您可以使用^[0-9]{1,10}

答案 1 :(得分:2)

只需使用 maxlength 属性而无需指令

<input type="text" class="form-control" ng-model="sample" maxlength="10">

修改 将其更改为type =&#34; number&#34;如果你想只有数字,

 <input type="number" class="form-control" ng-model="sample" maxlength="10">