0
votes

I just want to restrict user to input only 10 digits in a mobile number field. I have tried this code

 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;  
                    }  
                });  
            }  
        }  
    }); 

This code allow users to input the numbers but it's taking more than 10 digits. can anyone tell me how to restrict ofr only 10 digits only?

Any help will be appreciated. Thanks in advance....

2

2 Answers

3
votes

You could also try using ng-pattern:

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

This would require exactly 10 digits, and nothing else, for validation to pass. If you instead require a maximum of 10 digits, but fewer digits than this also acceptable, then you could use ^[0-9]{1,10}.

2
votes

Just use maxlength attribute without directive

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

EDIT Change it to type="number" if you want to have only numbers,

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