bang
bang

Reputation: 201

Using ng-currency for input validation on the UI

I'm using the ng-currency directive (found here) to fulfill some input validation on a project and would like to make some changes to the source code.

Currently, while the directive takes any form of input from the user, it does all the filtering on the data model only. E.g. even if the input field has "ABC" in it, the model value remains unchanged because it is not real currency input, but the view takes all alphanumeric characters and symbols. This is almost perfect but only half the job for my case, as I want to block any illegal characters from being keyed on the actual input UI (where illegal characters are anything other than 0-9 digits, a period ('.'), and a dash ('-')). Demo of directive here

I've made a Regex which I believe handles the cases I need (an optional '-' sign only at the beginning of the input that can only appear once to denote negative currency values; and restriction to 0-2 decimal points after an optional '.', which also can only appear once)

[-]?[\d]+[.]?[\d]{0,2}

Now my issue is that I am fairly new to Angular and JS so I am unsure where to place this regex in the directive I am using, let alone how to achieve this desired result. I would also like to set the maxlength attribute to 11 characters within this directive but again, it's been overwhelming for a beginner who only recently learned about ng-repeat and other angular patterns to navigate through this directive. I have a hunch that I would add an element.on('keypress') function that would test the regex pattern, but again it's only a hunch and I'd like to consult the experienced before I attempt to spend more time figuring this out.

Any and all help is greatly appreciated, thanks for your attention.

Upvotes: 1

Views: 4740

Answers (1)

Luis Aguirre
Luis Aguirre

Reputation: 81

You should use a directive to restrict characters on keydown.

Based on this directive you can customize it to:

angular.module('app').directive('restrictTo', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var re = RegExp(attrs.restrictTo);
        var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;

        element[0].addEventListener('keydown', function(event) {
            var v=element[0].value + event.key;
            if (!exclude.test(event.key) && !re.test(v)) {
                event.preventDefault();
            }
        });
    }
  }
});

And this to your input

<input type="text" ng-model="value" ng-currency restrict-to="[-0-9.]$">

You can see the demo here

Edit: Thanks to Bang for new regexp. It's much better than original.

Edit: Use this instead restrict-to="[-0-9.]$" as the goal is to restrict to 0 - 9 and the . (and - perhaps; not sure how that is a valid currency)

Upvotes: 3

Related Questions