Kalaiyarasi M Kalaiyarasi M - 5 months ago 35
AngularJS Question

How to fix size of the number before decimal point in Angularjs?

I am using the below code to fix the type of the field.

I have field named as "Marks %" which should allow only numbers and decimals that too it should allow only two digits before decimal point and two digit after decimal point.

My HTML :

<div ng-app="jmApp">
<h2>Validate Price</h2>
<div ng-controller="MainCtrl">

<input type="text" ng-model="salary" valid-number />
</div>
</div>


My Controller :

var app = angular.module('jmApp', []);

app.controller('MainCtrl', function($scope) {
});

app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}

ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
var val = '';
}

var clean = val.replace(/[^0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if(!angular.isUndefined(negativeCheck[1])) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean =negativeCheck[0] + '-' + negativeCheck[1];
if(negativeCheck[0].length > 0) {
clean =negativeCheck[0];
}

}

if(!angular.isUndefined(decimalCheck[1])) {
decimalCheck[0] = decimalCheck[0].slice(0,2);
decimalCheck[1] = decimalCheck[1].slice(0,2);
clean =decimalCheck[0] + '.' + decimalCheck[1];
}

if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});

element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});


OUTPUT :

It is allowing only numbers.
It will consider only two digits after decimal point.
If I entered any number of digits followed by decimal point it accepts only first two digits and decimal point.


But if I entered whole numbers then it is considering multiple numbers.

Can anyone please help me how to limit the size of whole numbers or if multiple digits entered also it need to consider only first two digits as it is considering when decimal point is placed.

Answer

You can use a custom directive for that.

Something like :

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {

});

app.directive("marksRegex", function() {

  var regexp;
  return {
    restrict: "A",
    link: function(scope, elem, attrs) {
      regexp = /^([0-9]([0-9]([\.]([0-9]([0-9]?)?)?)?)?)?$/;
      var char;
      elem.bind("keypress", function(event) {
        if (event.which == 8) return;
        char = String.fromCharCode(event.which);
        if (!regexp.test(elem.val() + char))
          event.preventDefault();
      })
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <label>Marks %:</label>
    <input type="text" marks-regex>
  </div>
</div>