Question

I have a custom directive, made after filters on ng-model in an input, that restricts input just to digits:

     .directive('onlydigitinput', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
                  .replace(/[^0-9]+/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
})

works great alone, but used together with, apparently, standard directive required, it starts to fail.

I use the following HTML (jade syntax):

input(type='text' , required, onlydigitinput,  min='1', max='99', maxlength='2')

(I do not use type='number' as it messes with maxlength: maxlength ignored for input type="number" in Chrome, and also disregards my directive as well)

When I enter digits, it works fine. Field is valid. When I try to enter digit and then some letter, it works fine: field is valid, and I can not enter non-digit. But when I start from non-digit, field is invalid but I can still enter letters, that is accompanied by the following error:

TypeError: Cannot read property 'toLowerCase' of undefined
at http://localhost:3000/scripts/core/directives/systemDirectives.js:63:54

referring to the use of toLowerCase in directive above. Please advice how I can clear this error and make my directive perform well also in the latter case, and avoid the error.

Was it helpful?

Solution

You have a required field validator on the input field. Hence, when you set the field to blank("") - happens when you type non-digit. The value becomes undefined.

var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
              .replace(/[^0-9]+/g, '');
            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

Add the below on top of above code:

if(!inputValue) return ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top