TheKingPinMirza
TheKingPinMirza

Reputation: 8952

angular validate input type=“number” validation issue

I was having an issue with input type number validation when user enters character.

It just got disappear when user tab out.

After little reseach i found couple of solutions and the best one is link

The solution given here is to use the following directive

app.directive('toNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$parsers.push(function (value) {
                return parseFloat(value || '');
            });
        }
    };
});

This solution works fine if user try to enter 1st character other than number. However it does not work when user enters lets say 1W. It allows to enter this pattern.

Probably, i need to modify this directive to blovk 1W, 1.W, 1WWW (any character after valid number) patterns to be blocked from entering.

Any help?

Also,

please share if there is any better solution to what i am looking for. My problem is: on IE, when user enters character in input type number and tab out, the number just disappear and i am unable to show error using angular $error.

Upvotes: 0

Views: 124

Answers (1)

Sumodh S
Sumodh S

Reputation: 741

Try this directive

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

Upvotes: 1

Related Questions