0

I am trying to set a decimal mask with two digits to my javascript application. I tried to use the following solution since I am using ui-mask across all the masks that I have at the moment:

<input id="DebitValue" type="text" placeholder="{{appResources.ContractCreateEditPaymentValuePlaceholder}}" ng-model="DebitValue" ui-mask-placeholder ui-mask="?9?9??9?9?9?9?.?9?9?" model-view-value="true" name="DebitValue" required>

But I am failing to achieve what I want, since I can not for instance insert 0.99 as value, I would need to insert 000000.99.

I checked this solution also, but neither the numeric or inputmask did nothing to my input, I just was able to write whatever I wanted.

Rui Queirós
  • 125
  • 1
  • 8

1 Answers1

0

You can use ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" to accept only numbers with a maximum of 2 decimal places and with a dot separator.

If you want something more, then use a directive like:

.directive('currencyInput', function ($browser, $filter) {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModel) {
            var listener = function () {
                var value = $element.val().replace(/,/g, '');
                $element.val($filter('number')(value, 0));
            };

            // This runs when we update the text field from element
            ngModel.$parsers.push(function (viewValue) {
                return parseInt(viewValue.replace(/,/g, ''), 10);
            });

            // This runs when the model gets updated on the scope directly and keeps our view in sync
            ngModel.$formatters.push(function (modelValue) {
                return modelValue == null || modelValue.length === 0 ? '' : $filter('number')(modelValue, 0);
            });

            ngModel.$viewChangeListeners = function () {
                $element.val($filter('number')(ngModel.$viewValue, 0))
            }

            $element.bind('change', listener);
            $element.bind('keypress', function (event) {
                var key = event.which;
                // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                // This lets us support copy and paste too
                if (key === 0 || key === 8 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
                    return;
                }
                $browser.defer(listener); // Have to do this or changes don't get picked up properly
            });
            $element.bind('paste cut', function () {
                $browser.defer(listener);
            });
        }
    }
})

Then use it on input elements, let's say:

<input currency-input ng-maxlength="10" ng-model="myDecimal" type="text">

If you want just two decimals, you should either hardcode number filter or receive it as parameter to directive:

$element.val($filter('number')(value, 2));
Cosmin
  • 147
  • 7