0

I currently have a lot of type=number input fields in a form with min and max validation. The input field will display an error message if user enters more than 6 digits for a 6 digit max number field.

But now I have this requirement to format numbers with commas. I know that you cannot enter comma in type=number input fields. If I make it a text field and add a directive to format the string, now the value becomes a string and I cannot perform min/max validation and also the value is stored as a string and not number.

I need help with figuring out how to format the number with commas and as well as add min/max validation and store it as a number not a string.

Mona
  • 45
  • 1
  • 8
  • 1
    Possible duplicate of [Localization of input type number](https://stackoverflow.com/questions/13412204/localization-of-input-type-number) – Heretic Monkey May 07 '19 at 21:37
  • The [candreoliveira/ngMask](https://github.com/candreoliveira/ngMask) plugin for AngularJS has a good examples of how to do that. – georgeawg May 08 '19 at 00:47

1 Answers1

0

You can achieve the desired result using a directive that limits the amount of characters.

myApp.directive("limitTo", [function() {
    return {
        restrict: "A",
            link: function(scope, elem, attrs) {
            var limit = parseInt(attrs.limitTo);
            angular.element(elem).on("keypress", function(e) {
                var char = String.fromCharCode(e.which);
                if (e.which != 8 && e.which != 0) {
                    if (char < '0' || char > '9') {
                        e.preventDefault();
                    }
                    else if (this.value.length == limit) {
                        e.preventDefault();
                    }
                }
            });
        }
    }
}]);

And then your input field would like something like:

<input type="number" limit-to="6">

This doesn't exactly format the input however it excludes certain characters from being entered by character code. You can allow commas to be added to the input by adding more conditionals to the if statement based upon character code. If you want to format this, then i'd recommend using an ng-pattern and a regex to get the exact formatting that you'd like.

Lastly, i'd recommend using angularjs form validation. https://docs.angularjs.org/guide/forms It is very handy for exactly what you are trying to do.