Hamed Ali Khan
Hamed Ali Khan

Reputation: 1118

Restrict input as numbers on input fields using AngularJS

I am trying to restrict input as numbers on below fields

Postal Code:
<input type="text" id="zipCode1" name="zipCode1" size="4" maxlength="5" ng-model="zipCode1" ng-change="myNumbers(zipCode1)" />
<input type="text" id="zipCode2" name="zipCode2" size="3" maxlength="4" ng-model="zipCode2" ng-change="myNumbers(zipCode2)" />

it doesn't work with

$scope.myNumbers = function(fieldName){
var tN = fieldName.replace(/[^\d]/g, "");
    if(tN != fieldName)
    fieldName = tN
};

It works with below code but changing both the fields

$scope.$watch('myNumbers', function() {
var tN = $scope.myNumbers.replace(/[^\d]/g, "");
    if(tN != $scope.myNumbers)
    $scope.myNumbers = tN;
})

Need to change the value for the input field where user is typing and not both

Upvotes: 3

Views: 14773

Answers (3)

ragnar
ragnar

Reputation: 1302

Here is a directive I've done to restrict the keys allowed.

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) {
                if (!exclude.test(event.key) && !re.test(event.key)) {
                    event.preventDefault();
                }
            });
        }
    }
});

And the input would look like:

<input type="text" name="zipCode1" maxlength="5" ng-model="zipCode1" restrict-to="[0-9]">

The regular expression evaluates the pressed key, not the value.

It also works perfectly with inputs type="number" because prevents from changing its value, so the key is never displayed and it does not mess with the model.

Upvotes: 3

Pauli Price
Pauli Price

Reputation: 4237

Use the directive found here: https://stackoverflow.com/a/19675023/149060 instead of the ng-change function. Replicated here for easy reference:

angular.module('app').
  directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel) return;
            ngModel.$parsers.unshift(function (inputValue) {
                var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' '); }).join('');
                ngModel.$viewValue = digits;
                ngModel.$render();
                return digits;
            });
        }
    };
});

Upvotes: 5

TestersGonnaTest
TestersGonnaTest

Reputation: 1027

You could try adding to the inputs

ng-pattern='/^\d{2}$/'

Upvotes: 3

Related Questions