2

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

3 Answers 3

3

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 (^).

Sign up to request clarification or add additional context in comments.

Comments

0

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

P.S. I have not tested.

Comments

0

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]/, '');

2 Comments

no its not accepting 0 at all.. I guess this is what you wanted??
No I just want no leading 0. it should accept 10, but not 01.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.