ccccccc
ccccccc

Reputation: 99

Input field that accept only positive numbers, two decimals and decimal comma, How?

I have trying to do a directive which accepts only positive numbers, comma for decimals like European used to do and two decimals in that input field.

Not succeeded to do that.

I'm quite new with AngularJS and especially with directives like this.

Has anyone of you idea or sample how to implement this?

Input field with this directive should accept only positive numbers not any characters or other signs expect comma to indicate that two decimal numbers is needed.

Eg. 123.34 => 123,34 or 123.345 123,34 etc.

I have tried both in palce edit and formatting after losing focus from tht kind of field.

Any samples around?

Br Michael

Upvotes: 1

Views: 8354

Answers (2)

Ben Lesh
Ben Lesh

Reputation: 108491

What you want to do is non-trivial.

There are a LOT of localization considerations, and a lot of implications when parsing your number to return it to the model. While Angular has a formatter in the form of the number filter, it currently does not have a parser. So handling arbitrary entry from a text input will not be pleasant.

Prior to Angular, I spent time working on such a JavaScript implementation for a banking institution, and it was a lot more work than it appeared on the surface.

In truth, the easy win for something of this sort would be to leverage angular's number or currency filters to output a "preview" of sorts next to a standard number input:

<input type="number" step="0.01" ng-model="foo"/> 
<output>{{ foo | number: 2 }}</output>

or

<input type="number" step="0.01" ng-model="foo"/> 
<output>{{ foo | currency }}</output>

The advantage here is Angular will handle the localization for you. You could even show/hide the output while the input is focused, I suppose.

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Its not exactly what you are looking for but this is direction:

Here we add commas and user can enter only integer.

enter image description here

fessmodule.controller('fessCntrl', function ($scope) {
    $scope.test = 123456879;
});

fessmodule.$inject = ['$scope'];


fessmodule.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter('number')(plainNumber));
                return plainNumber;
            });
        }
    };
}]);

Demo Fiddle

Upvotes: 3

Related Questions