1

How to enter decimal value upto two decimal place in textbox.please let me know how to modify this below directive.

I have used below code

app.directive('nksOnlyNumber', function () {
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            scope.$watch(attrs.ngModel, function (newValue, oldValue) {
                var spiltArray = String(newValue).split("");
                if (spiltArray.length === 0) return;
                if (spiltArray.length === 1
                     && (spiltArray[0] == '-'
                     || spiltArray[0] === '.')) return;
                if (spiltArray.length === 2
                     && newValue === '-.') return;

                /*Check it is number or not.*/
                if (isNaN(newValue)) {
                    ngModel.$setViewValue(oldValue);
                    ngModel.$render();
                }
            });
        }
    };
});
user1149278
  • 21
  • 3
  • 7

1 Answers1

1

I would do it using ng-pattern on the input, so I could use a regex and angular's built-in validation framework.

<input type="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" name="somenumber" ng-model="data.somenumber" />

http://plnkr.co/edit/b2G5YujiwQBdv5lDjIOc?p=preview

I found this regex here: Simple regular expression for a decimal with a precision of 2

Community
  • 1
  • 1
lmyers
  • 2,654
  • 1
  • 24
  • 22