2

I want to remove or trim zero as first or before the valid number in input text field.

I have a text field and am restricting the user to enter only numbers. When I enter the value as "0145" it should read as "145".

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

JavaScript:

angular.module('myApp', []).directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary for when using ng-required on your input. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9]/g, ''); 
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

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

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

JSFiddle

2 Answers 2

2

Change your regex to:

var transformedInput = inputValue.replace(/^[^1-9]*|[^0-9]/g, ''); 
Sign up to request clarification or add additional context in comments.

Comments

2

Your regex is slightly wrong. It should be:

var transformedInput = inputValue.replace(/^0*/g, '')

This will replace all the 0's at the beginning of the string

Comments

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.