user1149278
user1149278

Reputation: 21

Enter only decimal value upto two decimal place in angular js

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

Upvotes: 1

Views: 4821

Answers (1)

lbrazier
lbrazier

Reputation: 2654

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

Upvotes: 1

Related Questions