简体   繁体   中英

Angular Directive for input Numbers only

I am creating a directive to restrict input box to accept numbers only. It should accept 1-9999999999, but no leading 0. It is working but after entering first number it is accepting all numbers and characters. Please help me to resolve this.it should accept 10, but not 01. For this my code is,

HTML:

<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />

JS:

angular.module('myApp', []).directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/^[^1-9]*/g, ''); 
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});

function MyCtrl($scope) {
    $scope.number = ''
}

FIDDLE: FIDDLE

Just add an alternative ^0+ to /[^0-9]+/g so that the leading zeros could be removed:

var transformedInput = inputValue.replace(/^0+|[^0-9]+/g, ''); 
//                                         ^^^              

See updated fiddle .

The ^0+ matches 1 or more ( + ) zeros that are at the string start ( ^ ).

I have found this working fiddle (not created by me). Hope this helps.

Directive:

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


        ctrl.$formatters.unshift(function (a) {
            return $filter(attrs.format)(ctrl.$modelValue)
        });


        ctrl.$parsers.unshift(function (viewValue) {
            var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
            elem.val($filter(attrs.format)(plainNumber));
            return plainNumber;
        });
    }
};
}]);

PS I have not tested.

well you just need to remove the first ^ from your pattern. here is updated fiddle

use this -

replace(/[^1-9]*/g, '');

you can use the below one to restrict 0 at beginning updated fiddle -

replace(/^0|[^0-9]/, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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