CodeSnips

Saturday, July 19, 2014

AngularJS Number Validator Directive

After some searching yielded a few hints and examples, none of which really worked all that well, I pieced this together. Hopefully others will find it useful.

This AngularJS directive validates numeric entry. It uses a regular expression to test whether the input matches the expected numeric format and set the validity state of the element.

How does this work?
The $parsers array is an array of functions which can test the value on the input element. They pass the value along to other parsers by returning the value.  I change the value by removing any commas so the returned numeric string can be used as a Number.

In the directive, I capture the value of the directive attribute and add a parser function and formatter function to the respective arrays passed in.

The $formatters array is an array of functions which can format the model value for display in the input element. I use the built-in "numberFilter" for this.



View/Run/Edit the example in Plunker


app.directive('isNumber', ['numberFilter',function(numberFilter){
    return{
        require:'ngModel',
        link: function(scope, elem, attrs, ctrl){
            var digits = attrs.isNumber.length===0 ? "2" : attrs.isNumber;
            ctrl.$parsers.unshift(checkForNumber);
            ctrl.$formatters.unshift(formatNumber);

            function checkForNumber(viewValue){

                // Checks for positive or negative decimal or integer number with or without thousand separators
                if (/^-{0,1}\d{1,3}(,\d{3})*\.{0,1}\d*$|^-{0,1}\d*\.{0,1}\d*$/.test(viewValue)) {
                    ctrl.$setValidity('isNumber',true);
                }
                else{
                    ctrl.$setValidity('isNumber', false);
                }
                return viewValue.replace(/,/g,'');
            }

            function formatNumber(viewValue) {
                return numberFilter(viewValue,digits);
            }
        }
    };
}]);

1 comment:

  1. Tutorial and subject on angularjs mentioned on this blog was like attending online Angularjs training. Thanks for the step by step instructions with presentation.

    ReplyDelete