Reputation: 75
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 = ''
}
Upvotes: 2
Views: 2514
Reputation: 477
Change your regex to:
var transformedInput = inputValue.replace(/^[^1-9]*|[^0-9]/g, '');
Upvotes: 2
Reputation: 763
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
Upvotes: 2